Various Usage and Comparison of C List Sorting
- 2021-11-10 10:29:09
- OfStack
The following describes the usage and comparison of sort of various List
First, we create an entity of People with attributes of name, age and sex. The field we want to sort is age 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 = " Male "},
new People() {age=25, name = " Chen Jingtao ", sex = " Male "},
new People() {age=9, name = " Hui'an ", sex = " Male "},
new People() {age = 45, name = " Receipt ", sex = " Female "},
new People() {age=3, name = " Xiao Gull ", sex = " Female "},
new People() {age=70, name = " Wang Mo ", sex = " Male "}
};
1. The first sort 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 that the first method is troublesome to compare prices, so you need to create a new class to do it
2. The second sort method, using delegates to sort
peoples.Sort(delegate (People p1, People p2) { return p1.age.CompareTo(p2.age); });
It is very convenient to look at the delegate, so it is not so troublesome to create a new class.
3. The second sort method uses Lambda expression to sort
peoples.Sort( (a, b) =
>
a.age.CompareTo(b.age) );
There are three ways to sort visually, but I think Lambda expression is convenient to use.
Through this article, I hope to help you. Thank you for your support to this site!