happyboy200032的博客

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

//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);

     }

 }

评论

技术经验积累

© happyboy200032的博客 | Powered by LOFTER