測試環境
- OS:Windows 7 64bit
- IDE:Visual Studio 2010
- Project Type:Web From Developer
- Framework: ASP.NET 4
狀況描述:
- 想要使用Collection系列組件的Sort對複雜形態物件做排序。
解決方式:
- 使用comparison
實作範例:
- Dog.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Dog 的摘要描述
/// </summary>
public class Dog
{
public Dog(string name=null , int dogID=-1)
{
this.Name = name;
this.DogID = dogID;
}
private string name;
public string Name
{
get
{
return this.name;
}
set
{
if (this.name != value)
{
this.name = value;
}
}
}
private int dogID;
public int DogID
{
get
{
return this.dogID;
}
set
{
if (this.dogID != value)
{
this.dogID = value;
}
}
}
}
- ObjectSortUT.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
public partial class ObjectSortUT : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//這個是泛型宣告,這裡是說這個List內只能放Dog型態的物件
List<Dog> dogs = new List<Dog>();
//亂數產生器
Random rd = new Random();
for (int i = 0; i < 10; i++)
{
//加入一個Dog,傳入兩個數值
dogs.Add(new Dog( string.Format("小狗{0}",i) , rd.Next(10, 101)));
}
string result = "";
//取得目前List中狗物件的順序
foreach (Dog dog in dogs)
{
result += string.Format("DogID = {0} ", dog.DogID);
}
//輸出於瀏覽器
Response.Write(result + "</br>");
//好了請問該如和使用List的sort排序?
//請用
dogs.Sort(coustomerSort);
//在印一次,我懶得抽函式用copy貼的方便測試
result = "";
foreach (Dog dog in dogs)
{
result += string.Format("DogID = {0} ", dog.DogID);
}
//輸出於瀏覽器
Response.Write(result + "</br>");
}
//一個針對Dog物件排序的method
private int coustomerSort(Dog v1 , Dog v2)
{
return Math.Abs(v1.DogID) - Math.Abs(v2.DogID);
}
}
執行結果:
DogID = 23 DogID = 66 DogID = 32 DogID = 84 DogID = 64 DogID = 94 DogID = 79 DogID = 78 DogID = 38 DogID = 83
DogID = 23 DogID = 32 DogID = 38 DogID = 64 DogID = 66 DogID = 78 DogID = 79 DogID = 83 DogID = 84 DogID = 94
DogID = 23 DogID = 32 DogID = 38 DogID = 64 DogID = 66 DogID = 78 DogID = 79 DogID = 83 DogID = 84 DogID = 94
檔案夾結構:
後記:
- 為了程式碼的好維護,通常若是內部有的功能,如非特別需要優化的演算法,大多使用內建函式,因為內建函式也已經做了一定性的優化,通常會比自己寫的排序速度更快,若自己在寫一個bubble sort,會容易發生讓其他為護人員增加維護負擔。
沒有留言:
張貼留言