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.