对象数组自定义排序--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()); //按持续时间降序排序