使用system.collections.arraylist.sort()对象数组自定义排序

 

其核心为比较器的实现,比较器为一个类,继承了icomparer接口并实现int icomparer.compare(object x, object y)方法,该方法实现自定义排序的比较方式,可以通过使用不同的比较器对对象数组进行不一样的排序,可以自定义排序的基准字段和排序方式。

比较器的实现如下:

/// <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(需要排序的)如下:

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()); //按持续时间降序排序