C# List<T>自定义排序方法

原文地址:http://happyboy200032.blog.163.com/blog/static/469031132011111654345686/
(以下内容均为转载)
//C#范型List类的Sort方法有四种形式,分别是
//1,不带有任何参数的Sort方法----Sort();
//2,带有比较器参数的Sort方法 ----Sort(IComparer<T>)
//3,带有比较代理方法参数的Sort方法----Sort(Comparison<(Of <(T>)>))
//4,带有比较起参数,可以指定排序范围的Sort方法----Sort(Int32, Int32 IComparer(T))

//首先介绍第一种方法,使用这种方法不是对List中的任何元素对象都可以进行排序,List中的元素对象必须继承IComparable接口,并且要实现IComparable接口中的CompareTo()方法,在CompareTo()方法中要自己实现对象的比较规则。详细可以参照如下代码:

using System;
using System.Collections.Generic;
using System.Text;

namespace Comparer.SortObject
{
    /// <summary>
    /// List<>.Sort()的测试对象,类自己实现IComparable接口,
    /// 当需要对List中的SortTestObj1对象进行排序时,直接调用
    /// Sort()方法就可以了。
    /// </summary>
    public class SortTestObj1:IComparable
    {
        #region 类字段定义
        private int code;
        private string name;
        #endregion

        public SortTestObj1()
        {
        }

        #region 属性定义
        public int Code
        {
            set { this.code = value; }
            get { return this.code; }
        }
        public string Name
        {
            set { this.name = value; }
            get { return this.name; }
        }
        #endregion

        #region 实现比较接口的CompareTo方法
        public int CompareTo(object obj)
        {
            int res = 0;
            try
            {
                SortTestObj1 sObj = (SortTestObj1)obj;
                if (this.code > sObj.code)
                {
                    res = 1;
                }
                else if (this.code < sObj.code)
                {
                    res = -1;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("比较异常", ex.InnerException);
            }
            return res;
        }
        #endregion
    }
}

//第二种带有比较器参数的Sort方法,List中的元素对象不需要继承IComparable接口,但需要额外创建一个对象的比较器,下面的代码中的SortTestObj2类是准备要保存到范型List中的对象,SortTestObj2Camparer 类则是SortTestObj2类的比较器,这个比较起必须继承IComparer<T>接口,并且实现接口中的Compare()方法。详细做法可参照下面的代码。
//SortTestObj2类

using System;
using System.Collections.Generic;
using System.Text;

namespace Comparer.SortObject
{
    /// <summary>
    /// List<>.Sort(IComparer<(Of <(T>)>))的测试对象,类自己没有实现IComparable接口,
    /// 当需要对List中的SortTestObj2对象进行排序时,需要实例化一个SortTestObj2Camparer
    /// 类型的比较器,在比较器中指明排序类型(按Code排序还是按Name排序),然后调用
    /// xxxLst.Sort(SortTestObj2Camparer)方法就可以了。
    /// </summary>
    public class SortTestObj2
    {
        #region 类字段定义
        private int code;
        private string name;
        #endregion
        public SortTestObj2()
        {
        }

        #region 属性定义
        public int Code
        {
            set { this.code = value; }
            get { return this.code; }
        }
        public string Name
        {
            set { this.name = value; }
            get { return this.name; }
        }
        #endregion
    }
}

//SortTestObj2Camparer类

using System;
using System.Collections.Generic;
using System.Text;
using Comparer.SortObject;

namespace Comparer.Camparer
{
    [Flags]
    //排序类型定义
    public enum Obj2SortKind { Code, Name }
    /// <summary>
    /// SortTestObj2类排序用的比较器,继承IComparer<>接口,
    /// 实现接口中的Compare()方法。
    /// </summary>
    public class SortTestObj2Camparer : IComparer<SortTestObj2>
    {
        #region 类字段定义
        private Obj2SortKind sortKind;
        #endregion

        #region 构造器
        public SortTestObj2Camparer(Obj2SortKind sk)
        {
            this.sortKind = sk;
        }
        #endregion

        #region IComparer接口比较方法的实现
        public int Compare(SortTestObj2 obj1, SortTestObj2 obj2)
        {
            int res = 0;
            if ((obj1 == null) && (obj2 == null))
            {
                return 0;
            }
            else if((obj1 != null) && (obj2 == null))
            {
                return 1;
            }
            else if ((obj1 == null) && (obj2 != null))
            {
                return -1;
            }
 
            if (sortKind == Obj2SortKind.Code)
            {
                if (obj1.Code > obj2.Code)
                {
                    res = 1;
                }
                else if (obj1.Code < obj2.Code)
                {
                    res = -1;
                }
            }
            else if(sortKind == Obj2SortKind.Name)
            {
                res = obj1.Name.CompareTo(obj2.Name);
            }
            return res;
        }
        #endregion
    }
}

//第三种方法需要编写一个对象排序比较的方法,对List中的元素对象没有特殊的要求,但在比较方法中需要实现对象比较规则,这个方法实现后,就可以把这方名字作为参数委托给List的Sort方法,Sort方法在排序时会执行这个方法对List中的对象进行比较,详细可参照下面的代码。对List中元素我们还使用上面的SortTestObj2类对象。
static void Main(string[] args)
{
    //利用代理方法进行排序
    DelegateSort();
}
 
//Sort(Comparison<(Of <(T>)>))方法排序,这中方法需要先编写一个对象比较的方法,然后
//把这个比较方法委托给List的Sort方法。
//对象比较的方法
private static int SortTestObj2Compare(SortTestObj2 obj1, SortTestObj2 obj2)
{
     int res = 0;
     if ((obj1 == null) && (obj2 == null))
     {
         return 0;
     }
     else if ((obj1 != null) && (obj2 == null))
     {
         return 1;
     }
     else if ((obj1 == null) && (obj2 != null))
     {
         return -1;
     }
     if (obj1.Code > obj2.Code)
     {
         res = 1;
     }
     else if (obj1.Code < obj2.Code)
     {
         res = -1;
     }
     return res;
 }

 //List的委托排序
 private static void DelegateSort()
 {
     List<SortTestObj2> objLst = new List<SortTestObj2>();
     SortTestObj2 obj1 = new SortTestObj2();
     obj1.Code = 3;
     obj1.Name = "TestObj1";
     objLst.Add(obj1);
     SortTestObj2 obj2 = new SortTestObj2();
     obj2.Code = 2;
     obj2.Name = "TestObj2";
     objLst.Add(obj2);
     SortTestObj2 obj3 = new SortTestObj2();
     obj3.Code = 4;
     obj3.Name = "TestObj4";
     objLst.Add(obj3);
     SortTestObj2 obj4 = new SortTestObj2();
     obj4.Code = 1;
     obj4.Name = "TestObj3";
     objLst.Add(obj4);
     SortTestObj2 obj5 = new SortTestObj2();
     obj5.Code = 6;
     obj5.Name = "TestObj6";
     objLst.Add(obj5);
     objLst.Sort(SortTestObj2Compare);
     Console.WriteLine("委托方法排序的结果");
     foreach (SortTestObj2 item in objLst)
     {
         Console.WriteLine("Code=" + item.Code + ",Name=" + item.Name);
     }
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值