星期五, 5月 23, 2008

簡單的實做Generic Collection Sorting

再使用Generic Collection常常會有需要用到sort這功能..有兩種方法可以達到你的目的..
1.在型別上實做Icomparable介面
2.可以建立IComparer比較器

我就直接用List<>去作1這方式..簡單直覺..不過功能沒有IComparer強悍啦..直接看原始碼..

class person : IComparable<person>
{
public int height;
public string name;

#region IComparable<person> Members

public int CompareTo(person other)
{
return this.height.CompareTo(other.height);
}

#endregion
}

上面是建立一個person的class..然後實做IComparer..
a.CompareTo(b)這是a大傳回1,a小傳回-1,相等傳回0..

//建立比較的List<>
List<person> p = new List<person> {
new person() { name = "a1", height = 155 } ,
new person() { name = "a2", height = 172 } ,
new person() { name = "a3", height = 190 } ,
new person() { name = "a4", height = 182 } ,
new person() { name = "a5", height = 197 } ,
new person() { name = "a6", height = 161 }
};

//排序
p.Sort();

//迴圈去跑結果
string str = string.Empty;
foreach (person dd in p)
{
str += dd.name + " " + dd.height.ToString() + "\n";
}

MessageBox.Show(str);

執行..就可以看出結果了..

ddddfsdafa

如果你想由大排序到小..你就在return this.height.CompareTo(other.height) * -1這樣就行了..
如果你要用IComparer去作..你可以參考瓶水相逢大大的範例..

沒有留言: