1、List.Sort (泛型 Comparison) 法
成都創(chuàng)新互聯(lián)公司長期為超過千家客戶提供的網(wǎng)站建設服務,團隊從業(yè)經(jīng)驗10年,關注不同地域、不同群體,并針對不同對象提供差異化的產(chǎn)品和服務;打造開放共贏平臺,與合作伙伴共同營造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為安岳企業(yè)提供專業(yè)的網(wǎng)站設計、網(wǎng)站建設,安岳網(wǎng)站改版等技術服務。擁有10多年豐富建站經(jīng)驗和眾多成功案例,為您定制開發(fā)。
此方法的參數(shù)是Comparison類型,其實是一個包含兩個參數(shù)的委托,因此使用此方法,我們只需要定義一個委托,其兩個參數(shù)均為Student類型,在委托實現(xiàn)的方法比較兩個Student對象的Age屬性即可。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GenericCompare { class Program { static void Main(string[] args) { Liststudents = new List (); 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接口類型,因此只要定義一個類實現(xiàn)此接口然后再調(diào)用此方法即可。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GenericCompare { class StudentCompare :IComparer{ 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 students = new List (); 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#中l(wèi)ist排序 http://www.studyofnet.com/news/531.html