对List排序处理
案例一、
class Program { static void Main(string[] args) { List<Student> stuList = new List<Student>(); Student obj1 = new Student(); obj1.id = 1; Student obj2= new Student(); obj2.id =2; Student obj3 = new Student(); obj3.id =3; Student obj4 = new Student(); obj4.id = 4; stuList.Add(obj1); stuList.Add(obj2); stuList.Add(obj3); stuList.Add(obj4); stuList.Add(obj2); //排序输出结果 Console.WriteLine("正常输出==》"); foreach (var item in stuList) { Console.WriteLine(item.id); } stuList.Sort(new T_Asc()); //传递接口实现类来实现排序(升序) //排序输出结果 Console.WriteLine("升序输出==》"); foreach (var item in stuList) { Console.WriteLine(item.id); } stuList.Sort(new T_Desc()); //传递接口实现类来实现排序(降序) //排序输出结果 Console.WriteLine("降序输出==》"); foreach (var item in stuList) { Console.WriteLine(item.id); } Console.ReadLine(); } public class T_Asc : IComparer<Student> { public int Compare(Student x, Student y) { return x.id.CompareTo(y.id); } } public class T_Desc : IComparer<Student> { public int Compare(Student x, Student y) { return y.id.CompareTo(x.id); } } public class Student { public int id { get; set; } } }
作者:chenze 出处:https://www.cnblogs.com/chenze-Index/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。 如果文中有什么错误,欢迎指出。以免更多的人被误导。 |