首先,我们建一个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. 第3种排序方法,使用Lambda表达式来排序
peoples.Sort( (a, b) => a.age.CompareTo(b.age) );
这3种方法,个人觉得还是Lambda表达式使用得方便。