C # List ordering various usages and comparisons _c# tutorials

Source: Internet
Author: User

The following describes the use and comparison of the sort of the list

First, we build a people entity that has the attributes of name, age, and sex, and the fields we want to sort on are ages

Create a new entity class

 public class people
  {public
    string name {get; set;}
    public int Age {get; set;}
    public string Sex {get; set;}
  }

Create a new list of data

  list<people> peoples = new List<people> ()
      {
        New people () {age = one, name= "alun", sex = "male"},
        new People () {age=25, name = "Chen Jingtao", sex = "man"},
        New people () {age=9, name = "Huian", sex = "man"},
        New people () {age = 45 , name = "Small Ticket", sex = "female"},
        New people () {age=3, name = "Xiao ou", sex = "female"},
        New people () {age=70, name = "Wangmo", sex = "Male"}
      };

1. The 1th sort of 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 ());

You can see the first method of parity trouble, to create a new class to do

2. The 2nd sort of method, using the delegate to sort

Peoples. Sort (Delegate (People P1, people p2) {return p1.age.CompareTo (p2.age);});

It's convenient to look at the delegates, without the hassle of creating new classes.

3. The 2nd sort of method, using lambda expressions to sort

Peoples. Sort ((A, B) => A.age.compareto (b.age));

There are 3 methods for visual sorting, and it is easy for individuals to think of lambda expressions.

Through this article hope to help you, thank you for your support to this site!

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.