您的位置:时时app平台注册网站 > 编程知识 > C# List 排序各种用法与比较

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

2019-10-30 04:16

 

2. 第2种排序方法,使用委托来排序

    public class PeopleAgeComparer : IComparer<People>
    {
        public int Compare(People p1, People p2)
        {
            return p1.age.CompareTo(p2.age);
        }
    }

peoples.Sort(new PeopleAgeComparer());
peoples.Sort(delegate (People p1, People p2) { return p1.age.CompareTo(p2.age); });

看委托的章程很有益于,不用新建类这么艰巨。

peoples.Sort( (a, b) => a.age.CompareTo(b.age) );

3. 第2种排序方法,使用兰姆da表明式来排序

    public class People
    {
        public string name { get; set; }
        public int age { get; set; }
        public string sex { get; set; }
    }

新建贰个实体类

能够看到第意气风发种办法比价麻烦,要新建二个新的类来做

 

 

新建list的数据

 

 

 

目测排序有那3种办法,个人认为依然Lambda表明式使用得实惠。

 

 

率先,大家建一个People的实体,有name、age、sex的质量,我们要排序的字段是年龄age

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

下边介绍各个List的sort的用法与相比

            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 = "男"}
            };

 

本文由时时app平台注册网站发布于编程知识,转载请注明出处:C# List 排序各种用法与比较

关键词: