C # sorting custom objects,
The Array object Array has an Sort method (click to view the implementation of the Sort method), which is specially used for sorting. Please refer
If we want to add a sort for our class, we only need to inherit the IComparable interface and implement the CompareTo method;
Call the CompareTo method to internally implement object comparison, and determine the object order through the return value
Negative value, current object <parameter object
Positive Value, current Object> parameter object
Zero. Two objects are equal.
Next, we will customize the object sorting method based on the interface.
1 class People: IComparable 2 {3 public uint Age {get; set;} 4 5 # region IComparable member 6 // implement a human sort by Age 7 public int CompareTo (object obj) 8 {9 var people = (People) obj; 10 if (this. age> people. age) 11 return 1; 12 else if (this. age <people. age) 13 return-1; 14 return 0; 15} 16 17 # endregion18}
1 static void Main(string[] args) 2 { 3 var arrs =new People[] { 4 new People{Age=15}, 5 new People{Age=24}, 6 new People{Age=13}, 7 new People{Age=18}, 8 new People{Age=14} 9 };10 11 arrs.ToList().ForEach(a => Console.Write("{0} ", a.Age));12 Array.Sort(arrs);13 Console.WriteLine("");14 arrs.ToList().ForEach(a => Console.Write("{0} ", a.Age));15 }