范型List的Sort方法
范型List类的Sort方法有四种形式
1,不带有任何参数的Sort方法----Sort();
2,带有比较器参数的Sort方法 ----Sort(IComparer<T>)
3,带有比较代理方法参数的Sort方法----Sort(Comparison<(Of <(T>)>))
4,带有比较器参数,可以指定排序范围的Sort方法----Sort(Int32, Int32, IComparer(T))
第一种:使用这种方法不是对List中的任何元素对象都可以进行排序,List中的元素对象必须继承IComparable接口,并且要实现IComparable接口中的CompareTo()方法,在CompareTo()方法中要自己实现对象的比较规则。
public class SortTestObj1:IComparable
{
private int code;
private string name;
public SortTestObj1()
{
}
public int Code
{
set { this.code = value; }
get { return this.code; }
}
public string Name
{
set { this.name = value; }
get { return this.name; }
}
//实现比较接口的CompareTo方法
public int CompareTo(object obj)
{
int res = 0;
try
{
SortTestObj1 sObj = (SortTestObj1)obj;
if (this.code > sObj.code)
{
res = 1;
}
else if (this.code < sObj.code)
{
res = -1;
}
}
catch (Exception ex)
{
throw new Exception("比较异常", ex.InnerException);
}
return res;
}
}
第二种:带有比较器参数的Sort方法,List中的元素对象不需要继承IComparable接口,但需要额外创建一个对象的比较器,这个比较器必须继承IComparer<T>接口,并且实现接口中的Compare()方法。
public class SortTestObj
{
....
}
public class SortTestObjCamparer : IComparer<SortTestObj>
{
public int Compare(SortTestObj obj, SortTestObj obj2)
{
...
}
}
第三种,第四种 (略)