前面介绍对象排序的方法之一是为对象定制Comparer
还有一种方法是:要排序的对象实现IComparable接口。
public class Stu : IComparable<Stu>
{
public string Class;
public int Code;
public int Age;
public enum Order { Class, Age, Code }
public static Order oder;
#region IComparable<Stu>
public int CompareTo(Stu other)
{
switch (oder)
{
case Order.Age:
return this.Age.CompareTo(other.Age);
case Order.Class:
return this.Class.CompareTo(other.Class);
case Order.Code:
return this.Code.CompareTo(other.Code);
default:
return this.Code.CompareTo(other.Code);
}
}
#endregion
}
下面是排序的代码::::
List<Stu> stus = new List<Stu>();
Stu.oder = Stu.Order.Age;
Random rand=new Random();
for (int i = 0; i < 10; i++)
{
Stu stu = new Stu();
stu.Age = rand.Next(0,15);
stus.Add(stu);
}
stus.Sort();//排序