C# List 排序各類用法與比擬。本站提示廣大學習愛好者:(C# List 排序各類用法與比擬)文章只能為提供參考,不一定能成為您想要的結果。以下是C# List 排序各類用法與比擬正文
上面引見各類List的sort的用法與比擬
起首,我們建一個People的實體,有name、age、sex的屬性,我們要排序的字段是年紀age
新建一個實體類
public class People { public string name { get; set; } public int age { get; set; } public string sex { get; set; } }
新建list的數據
List<People> peoples = new List<People>() { new People() {age = 11, name="alun", sex = "男"}, new People() {age=25, name = "陳敬桃", sex = "男"}, new People() {age=9, name = "惠安", sex = "男"}, new People() {age = 45, name = "小票", sex = "女"}, new People() {age=3, name = "曉鷗", sex = "女"}, new People() {age=70, name = "望谟", sex = "男"} };
1. 第1種排序辦法,應用 IComparer
public class PeopleAgeComparer : IComparer<People> { public int Compare(People p1, People p2) { return p1.age.CompareTo(p2.age); } } peoples.Sort(new PeopleAgeComparer());
可以看到第一種辦法比價費事,要新建一個新的類來做
2. 第2種排序辦法,應用拜托來排序
peoples.Sort(delegate (People p1, People p2) { return p1.age.CompareTo(p2.age); });
看拜托的方法很便利,不消新建類這麼費事。
3. 第2種排序辦法,應用Lambda表達式來排序
peoples.Sort( (a, b) => a.age.CompareTo(b.age) );
目測排序有這3種辦法,小我認為照樣Lambda表達式應用得便利。
經由過程此文願望能贊助年夜家,感謝年夜家對本站的支撐!