首页 > 代码库 > c#中list sort排序
c#中list sort排序
1、List.Sort (泛型 Comparison) 法
此方法的参数是Comparison类型,其实是一个包含两个参数的委托,因此使用此方法,我们只需要定义一个委托,其两个参数均为Student类型,在委托实现的方法比较两个Student对象的Age属性即可。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GenericCompare { class Program { static void Main(string[] args) { List<Student> students = new List<Student>(); students.Add(new Student("001","kenshincui",25)); students.Add(new Student("002", "miaoer", 23)); students.Add(new Student("003", "shenjinjuan", 22)); students.Add(new Student("004", "nieyanxin", 24)); Console.WriteLine("未进行排序之前:"); foreach (Student st in students) { Console.WriteLine(st.No+","+st.Name+","+st.Age+";"); } Console.WriteLine("List.Sort (泛型 Comparison) 排序之后:"); students.Sort(delegate(Student a, Student b) { return a.Age.CompareTo(b.Age); }); foreach (Student st in students) { Console.WriteLine(st.No + "," + st.Name + "," + st.Age + ";"); } Console.ReadKey(); } } }
2、List.Sort (泛型 IComparer)
此方法需要一个泛型IComparer接口类型,因此只要定义一个类实现此接口然后再调用此方法即可。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GenericCompare { class StudentCompare :IComparer<Student> { public int Compare(Student a, Student b) { return a.Age.CompareTo(b.Age); } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GenericCompare { class Program { static void Main(string[] args) { List<Student> students = new List<Student>(); students.Add(new Student("001","kenshincui",25)); students.Add(new Student("002", "miaoer", 23)); students.Add(new Student("003", "shenjinjuan", 22)); students.Add(new Student("004", "nieyanxin", 24)); Console.WriteLine("未进行排序之前:"); foreach (Student st in students) { Console.WriteLine(st.No+","+st.Name+","+st.Age+";"); } Console.WriteLine("List.Sort (泛型 IComparer) 排序之后:"); students.Sort(new StudentCompare()); foreach (Student st in students) { Console.WriteLine(st.No + "," + st.Name + "," + st.Age + ";"); } Console.ReadKey(); } } }
参考资料: c#中list排序 http://www.studyofnet.com/news/531.html
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。