标签:
下面介绍各种List的sort的用法与比较
首先,我们建一个People的实体,有name、age、sex的属性,我们要排序的字段是年龄age
新建一个实体类
1 public class People 2 { 3 public string name { get; set; } 4 public int age { get; set; } 5 public string sex { get; set; } 6 }
新建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表达式来排序
1 peoples.Sort( (a, b) => a.age.CompareTo(b.age) );
目测排序有这3种方法,个人觉得还是Lambda表达式使用得方便。
FROM:http://www.cnblogs.com/alunchen/p/5895048.html
标签:
原文地址:http://www.cnblogs.com/chunhui212/p/5895810.html