The sort method of the List has three kinds of results 1,0,-1 are greater than, equal to, less than.
1. For a List of numeric types (list<int>), use sort directly.
List<int> scorelist=new list<int> () {89,100,78,23,67};
Scorelist.sort ();//default in ascending order, equivalent to: Scorelist.sort ((x,y) =>x.compareto (y))
Scorelist.sort ((x,y) =>-x. CompareTo (y));//descending order
2. For non-numeric types or custom types, you can sort by implementing the IComparable Interface rewrite CompareTo method:
public class Person:icomparable<person> {public string Name {get; set;}
public int Age {get; set;}
Comparetto: greater than 1; equal to 0; less than-1; public int CompareTo (person p) {int result; if (this. Name = = P.name && this.
Age = = P.age} {result = 0; else {//this.
The name of the following Mary P.name indicates that the previous Bob//mary is compared to Bob from a small to large, and if Mary and Bob are more than 0 (stating that Mary is greater than Bob), then Result=1 (description is in order of small to large) if (this.
Name.compareto (P.name) > 0)//first by name small to large Array {result = 1; else if (this. Name = = P.name && this.
Age > P.age)//name is the same as the same as the old from small to large {result = 1;
else {result =-1;
} return result; } Public ovErride string ToString () {return this. Name + "-" + this.
Age; }
}
list<person> Lstperson = new list<person> ();
Lstperson.add (new person () {Name = ' Bob ', age =});
Lstperson.add (new person () {Name = ' Mary ', age =});
Lstperson.add (new person () {Name = ' Mary ', age =});
Lstperson.add (new person () {Name = ' Lily ', age =});
Lstperson.sort ();
foreach (person item in Lstperson)
{
Console.WriteLine (item. ToString ());
}
Console.readkey ();
Output: Bob-19 Lily-20 Mary-17 Mary-18
or use LINQ sorting without implementing the IComparable interface:
list<person> Lstperson = new list<person> ();
Lstperson.add (new person () {Name = ' Bob ', age = 19});
Lstperson.add (new person () {Name = ' Mary ', age = 18});
Lstperson.add (new person () {Name = ' Mary ', age = 17});
Lstperson.add (new person () {Name = ' Lily ', age = 20});
Lstperson.sort ();
Lstperson.sort ((x, y) => {int result;
if (X.name = = Y.name && X.age = = y.age) {result = 0;
} else {if (X.name.compareto (Y.name) > 0) {
result = 1;
else if (x.name = Y.name && x.age > Y.age) {
result = 1;
else {result =-1; } return result;
}); foreach (person item in Lstperson) {Console.WriteLine (item.
ToString ()); } console.readkey ();
Output: Bob-19 Lily-20 Mary-17 Mary-18