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
原文地址:http://studyofnet.blog.51cto.com/8142094/1538944