C # usage and comparison of List sorting,

Source: Internet
Author: User

C # usage and comparison of List sorting,

 

The following describes the usage and comparison of various List sort

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

Create an object class

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

Create list Data

List <People> les = new List <People> () {new People () {age = 11, name = "alun", sex = "male"}, new People () {age = 25, name = "Chen Jingtao", sex = "male"}, new People () {age = 9, name = "Hui 'an ", sex = "male"}, new People () {age = 45, name = "small pass", sex = "female"}, new People () {age = 3, name = "Xiao ou", sex = "female"}, new People () {age = 70, name = "Wangmo", sex = "male "}};

 

1.1st sorting methods, using IComparer

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

We can see that the first method is too difficult to compare prices. We need to create a new class to do this.

 

 

2.2nd sorting methods, sorted by Delegation

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

It is very convenient to look at the delegate method, so you do not need to create a class that is so troublesome.

 

 

3.2nd sorting methods, sorted using Lambda expressions

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

 

 

 

There are three methods for visual sorting. I personally think Lambda expressions are easy to use.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.