The list <t> class can use the sort () method to sort elements.
The sort () method defines several overload methods, which are
Public void list <t>. Sort (), sort method without any parameters
Public void list <t>. Sort (comparison <t>), sort method with comparison proxy method parameters
Public void list <t>. Sort (icomparer <t>), sort method with comparator Parameter
Public void list <t>. Sort (int32, int32, icomparer <t>), with a comparison parameter, you can specify the sort method of the sorting range
First, introduce the first method: Public void list <t>. sort (). This method is not used to sort any element objects in the list. Element objects in the list must inherit the icomparable interface and implement the compareto () method in the icomparable interface, in the compareto () method, you must implement the object comparison rules by yourself.
int CompareTo(Object obj)
ParametersOBJ
-
Type: system. Object
Objects to be compared with this instance.
Return Value
Type: system. int32
A value that indicates the relative sequence of objects to be compared. The returned values are as follows:
Value |
Description |
Less Than Zero |
This instance is sorted before obj. |
Zero |
This instance and OBJ appear in the same order. |
Greater than zero |
This instance is sorted by obj. |
For details, refer to the following code:
/// <Summary> /// entity class of the unit subject formula /// </Summary> public class accountformular: icomparable {// <summary> // company ID /// </Summary> private string companyid; Public String companyid {get {return this. companyid;} set {This. companyid = value ;}/// <summary> // account name /// </Summary> private string accountname; Public String accountname {get {return this. accountname;} set {This. accountname = value ;}/// <summary> // budget year /// </Summary> private int budgetyear; Public int budgetyear {get {return this. budgetyear;} set {This. budgetyear = value ;}/// <summary> // budget formula /// </Summary> private string formular; Public String formular {get {return this. formular;} set {This. formular = value ;}} public int compareto (Object OBJ) {int flg = 0; try {accountformular sobj = (accountformular) OBJ; flg = This. accountname. compareto (sobj. accountname); // sort by "account name" first if (flg = 0) // if the account name is the same, then sort by the size of the "budget year" {If (this. budgetyear> sobj. budgetyear) {flg = 1;} else if (this. budgetyear <sobj. budgetyear) {flg =-1 ;}} catch (exception ex) {Throw new exception ("exception compared", Ex. innerexception) ;}return flg ;}}