Use the System.Collections.ArrayList.Sort() object array to customize sorting
Its core is the implementation of comparator, which is a class. It inherits the IComparer interface and implements the int IComparer.Compare(Object x, Object y) method. This method implements the comparison method of custom sorting. It can sort the object array differently by using different comparators, and can customize the benchmark field and sorting method of sorting.
The comparator is implemented as follows:
/// <summary> /// ArrayList.Sort()Comparator, will StateSectionModel Press ContiueTime Descending sort /// </summary> public class SSModelSort : IComparer { public int Compare(object x, object y) { StateSectionModel a = x as StateSectionModel; StateSectionModel b = y as StateSectionModel; if (x != null && y != null) { return Convert.ToInt32(b.ContinueTime - a.ContinueTime); } else { throw new ArgumentException(); } } }
The entity class StateSectionModel (to be sorted) is as follows:
public class StateSectionModel { /// <summary> /// state /// </summary> public int State { get; set; } /// <summary> /// start time /// </summary> public string StartTime { get; set; } /// <summary> /// End time /// </summary> public string EndTime { get; set; } /// <summary> /// Status duration /// </summary> public double ContinueTime { get; set; } }
Use example:
ArrayList ArrSSModel = new ArrayList(){ new StateSectionModel(1,"","",5.5), new StateSectionModel(1,"","",3.5), new StateSectionModel(1,"","",4.5)}; ArrSSModel.Sort(new SSModelSort()); //Sort by duration descending