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


    使用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()); //按持续时间降序排序
  • 相关阅读:
    Django-用户认证组件
    Django-session组件
    Axer-使用Msfvenom自动创建有效负载的工具
    CVE-2020-0668-Windows服务跟踪中的普通特权升级错误
    隐藏Web Shell
    404 not found Webshell
    渗透测试流程
    IIS inprocess
    分布式.Net
    WPF UnhandledException
  • 原文地址:https://www.cnblogs.com/xiaomengshan/p/11138650.html
Copyright © 2020-2023  润新知