澳门至尊网站-首页

您的位置:澳门至尊网站 > 软件综合 > 排序各种用法与比较

排序各种用法与比较

2019-10-27 14:14

 

上面介绍各类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表明式使用得低价。

本文由澳门至尊网站发布于软件综合,转载请注明出处:排序各种用法与比较

关键词: