常用的两种使用scort()进行排序的方法
- 对于List按照某一个字段的值进行排序,使用系统提供的sort方法进行排序,需要继承ICompare接口实现参数中的CompareTo方法,注意参数一定是Object。CompareTo方法只能进行两个数据的比较,但是系统可以实现对整个list中的数据的排序。
List<Student> stuList = new List<Student>(); stuList.Add(s1); stuList.Add(s2); stuList.Add(s3); stuList.Add(s4); stuList.Add(s5); stuList.Add(s6); for (int i = 0; i < stuList.Count; i++) { Console.WriteLine(stuList[i]); } Console.WriteLine("------------------------"); stuList.Sort(); for (int i = 0; i < stuList.Count; i++) { Console.WriteLine(stuList[i]); } public int CompareTo(object other) { return this.Age - ((Student)other).Age; }
ps:可以通过改变this.Age和other.Age的顺序控制是升序还是降序,方法的返回值必须和接口中的方法保持一致
- 参考多个字段进行排序
自己实现方法,方法的返回值必须是int,在sort中使用lambda表达式实现排序
可以通过设置权重来控制字段的优先级
List<Student> stuList = new List<Student>();
stuList.Add(s1);
stuList.Add(s2);
stuList.Add(s3);
stuList.Add(s4);
stuList.Add(s5);
多个方法之间要使用 + 号
stuList.Sort(((x, y) => x.sortByAge(y) * 4 + x.sortByChinese(y)));//系统规定必须是int
for (int i = 0; i < stuList.Count; i++)
{
Console.WriteLine(stuList[i]);
}
public int sortByAge(Student s)
{
int result = this.Age - s.Age;
return result==0?0:(result>0?1:-1);
}
public int sortByChinese(Student s)
{
int result= (int)(s.Chinese-this.Chinese);//变量的位置确定了正序还是倒序
return result == 0 ? 0 : (result > 0 ? 1 : -1);
}