您好,登錄后才能下訂單哦!
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
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。