下面介紹各種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表達式使用得方便。