The sort function without parameters in the List class can be used to sort elements in the List class, however, if the element types in the List class cannot be directly compared (such as user-defined struct and many classes), or you want to use a more flexible custom comparison method, you can solve this problem by inheriting the functions of the icomparer interface.
The sample code is as follows:
1) declare a class
/// <Summary> /// summary class /// </Summary> public class person {public string name; Public int age; Public override string tostring () {return "Name: "+ name +" Age: "+ age ;}}
2) declare a class that inherits the icomparer Interface
/// <Summary> /// compare the memory class instance size, and implement the interface icomparer // </Summary> public class personcomparer: icomparer <person> {public int compare (Person X, person y) {If (x = NULL & Y = NULL) return 0; If (x = NULL) Return-1; if (y = NULL) return 1; // todo: Comparison rules of the person class instance X and Y // sort by name from small to large. people with the same name are older than {int temp = string. compare (X. name, Y. name); If (temp> 0) Return-1; else if (temp <0) return 1; if (X. age> Y. age) return 1; if (X. age <Y. age) Return-1 ;}return 0 ;}}
3) create a list using the main function, use the rules in the newly created personcomparer class to sort the list.
Static void main (string [] ARGs) {list <person> A = new list <person> ();. add (new person () {name = "tsybius", age = 23});. add (new person () {name = "Galatea", age = 21});. add (new person () {name = "Lucius", age = 22});. add (new person () {name = "Septimus", age = 22});. add (new person () {name = "Octavius", age = 22});. add (new person () {name = "Lucius", age = 24}); // output all elements in a console. writeline ("Before sorting"); foreach (var v in a) {console. writeline (v. tostring ();} console. writeline ("-"); // sorts. sort (New personcomparer (); // outputs the console of all elements in. writeline ("sorted"); foreach (var v in a) {console. writeline (v. tostring ();} console. writeline ("-"); console. readline ();}
4) program running example
End