c# sort()自定義的結(jié)構(gòu)
用在arraylist。list等容器中sort().對(duì)自定義的結(jié)構(gòu)排序!
1 自定義結(jié)構(gòu)實(shí)現(xiàn)IComparable interface
如下:默認(rèn)按id排序





















































































compareto()也可以寫為:
if(this.ID < emp.ID)
return -1;
else if(this.ID==emp.ID)
return 0;
else
return 1;
但要實(shí)現(xiàn)多個(gè)選擇排序:
可以在類中加如:
public enum SortBy{ID,NAME,SALARY}
private static SortBy m_SortBy = SortBy.NAME;
public static SortBy SortBy
{
get{return m_SortBy;}
set{m_SortBy=value;}
}
重寫compareto() :
public int CompareTo(object obj)
{
if(!(obj is Employee))
throw new InvalidCastException("This object is not of type Employee");
Employee emp = (Employee)obj;
switch(m_SortBy)
{
case ArrayListSortingDemo.SortBy.ID:
return this.ID.CompareTo(emp.ID);
case ArrayListSortingDemo.SortBy.NAME:
return this.Name.CompareTo(emp.Name);
case ArrayListSortingDemo.SortBy.SALARY:
return this.Salary.CompareTo(emp.Salary);
default:
goto case ArrayListSortingDemo.SortBy.NAME;
}
2 要實(shí)現(xiàn)多種標(biāo)準(zhǔn)排序,還可以給sort()傳入自定義的比較函數(shù) int less(object 1,object 2)
3 還可以傳如Icomparare ,具體還不知道怎么用?希望指點(diǎn):-------------------
posted on 2006-03-10 14:37 夢(mèng)在天涯 閱讀(2582) 評(píng)論(1) 編輯 收藏 引用 所屬分類: C#/.NET