C# List 排序各种用法与比较

时间:2022-03-23 08:08:25

下面介绍各种List的sort的用法与比较

首先,我们建一个People的实体,有name、age、sex的属性,我们要排序的字段是年龄age

新建一个实体类

?
1
2
3
4
5
6
public class People
 {
   public string name { get; set; }
   public int age { get; set; }
   public string sex { get; set; }
 }

新建list的数据    

?
1
2
3
4
5
6
7
8
9
10
  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 = "男"}
      };
<br>

1. 第1种排序方法,使用 IComparer

?
1
2
3
4
5
6
7
8
9
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表达式使用得方便。

通过此文希望能帮助大家,谢谢大家对本站的支持!