C# List sorting various usages and comparisons

Sort numeric strings
string[] strs = { "1", "111", "11", "999", "77" };
            List<string> list = strs.ToList();
            list.Sort(delegate (string s1, string s2) { return int.Parse(s1).CompareTo(int.Parse(s2)); });

   

The following introduces the usage and comparison of various List's sort

First, we create a People entity with attributes of name, age, and sex. The field we want to sort is age.

Create a new entity class

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

New list data


            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 = ""female},
                new People() {age=3, name = "晓鸥", sex = ""},
                new People() {age=70, name = "望谟", sex = ""}
            };

 

1.  The first sorting method, using 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) );

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325897796&siteId=291194637