1、List.Sort (泛型 Comparison) 法

此方法的参数是Comparison类型,其实是一个包含两个参数的委托,因此使用此方法,我们只需要定义一个委托,其两个参数均为Student类型,在委托实现的方法比较两个Student对象的Age属性即可。

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceGenericCompare{classProgram{staticvoidMain(string[]args){List<Student>students=newList<Student>();students.Add(newStudent("001","kenshincui",25));students.Add(newStudent("002","miaoer",23));students.Add(newStudent("003","shenjinjuan",22));students.Add(newStudent("004","nieyanxin",24));Console.WriteLine("未进行排序之前:");foreach(Studentstinstudents){Console.WriteLine(st.No+","+st.Name+","+st.Age+";");}Console.WriteLine("List.Sort(泛型Comparison)排序之后:");students.Sort(delegate(Studenta,Studentb){returna.Age.CompareTo(b.Age);});foreach(Studentstinstudents){Console.WriteLine(st.No+","+st.Name+","+st.Age+";");}Console.ReadKey();}}}



2、List.Sort (泛型 IComparer)


此方法需要一个泛型IComparer接口类型,因此只要定义一个类实现此接口然后再调用此方法即可。

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceGenericCompare{classStudentCompare:IComparer<Student>{publicintCompare(Studenta,Studentb){returna.Age.CompareTo(b.Age);}}}usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceGenericCompare{classProgram{staticvoidMain(string[]args){List<Student>students=newList<Student>();students.Add(newStudent("001","kenshincui",25));students.Add(newStudent("002","miaoer",23));students.Add(newStudent("003","shenjinjuan",22));students.Add(newStudent("004","nieyanxin",24));Console.WriteLine("未进行排序之前:");foreach(Studentstinstudents){Console.WriteLine(st.No+","+st.Name+","+st.Age+";");}Console.WriteLine("List.Sort(泛型IComparer)排序之后:");students.Sort(newStudentCompare());foreach(Studentstinstudents){Console.WriteLine(st.No+","+st.Name+","+st.Age+";");}Console.ReadKey();}}}




参考资料: c#中list排序 http://www.studyofnet.com/news/531.html