對象數組自定義排序--System.Collections.ArrayList.Sort()

使用System.Collections.ArrayList.Sort()對象數組自定義排序

 

其核心爲比較器的實現,比較器爲一個類,繼承了IComparer接口並實現int IComparer.Compare(Object x, Object y)方法,該方法實現自定義排序的比較方式,能夠經過使用不一樣的比較器對對象數組進行不同的排序,能夠自定義排序的基準字段和排序方式。數組

比較器的實現以下:spa

/// <summary>
    /// ArrayList.Sort()比較器,將StateSectionModel按ContiueTime降序排序
    /// </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();
            }
        }
    }

實體類StateSectionModel(須要排序的)以下:code

public class StateSectionModel
    {
        /// <summary>
        /// 狀態
        /// </summary>
        public int State { get; set; }

        /// <summary>
        /// 開始時間
        /// </summary>
        public string StartTime { get; set; }

        /// <summary>
        /// 結束時間
        /// </summary>
        public string EndTime { get; set; }

        /// <summary>
        /// 狀態持續時間
        /// </summary>
        public double ContinueTime { get; set; }
    }

使用示例:對象

ArrayList ArrSSModel = new ArrayList(){
    new StateSectionModel(1,"","",5.5), 
    new StateSectionModel(1,"","",3.5),
    new StateSectionModel(1,"","",4.5)};
ArrSSModel.Sort(new SSModelSort()); //按持續時間降序排序
相關文章
相關標籤/搜索