首页 > 编程语言 > 详细

对象数组自定义排序--System.Collections.ArrayList.Sort()

时间:2019-07-05 16:28:14      阅读:119      评论:0      收藏:0      [点我收藏+]

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

 

对象数组自定义排序--System.Collections.ArrayList.Sort()

原文:https://www.cnblogs.com/xiaomengshan/p/11138650.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!