c#范型List的Sort方法详解

c#范型List的Sort方法详解

范型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);
            }
        }
   对于第四排序方法,实际是第二种比较器排序的一个扩展,在指定排序比较器的同时,指定排序范围,即List中准备排序的开始元素索引和结束元素索引,代码样式如下:

//按Name进行排序
            SortTestObj2Camparer nameCmp = new SortTestObj2Camparer(Obj2SortKind.Name);
            objLst.Sort(1, 3, nameCmp);
下面的代码是对上面介绍的四种方法的进行测试的代码,可以结合上面代码建立一个控制台工程体会一下。

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

namespace Comparer
{
    class Program
    {
        static void Main(string[] args)
        {
            //List中的对象实现了IComparable接口时的排序
            LstSort();
            //利用比较器排序
            LstComparerSort();
            //利用比较器,对List中指定的区间的元素排序
            LstFromToSort();
            //利用代理方法进行排序
            DelegateSort();
        }

        //Sort()方法排序
        private static void LstSort()
        {
            List<SortTestObj1> objLst = new List<SortTestObj1>();
            SortTestObj1 obj1 = new SortTestObj1();
            obj1.Code = 3;
            obj1.Name = "TestObj3";
            objLst.Add(obj1);
            SortTestObj1 obj2 = new SortTestObj1();
            obj2.Code = 2;
            obj2.Name = "TestObj2";
            objLst.Add(obj2);
            SortTestObj1 obj3 = new SortTestObj1();
            obj3.Code = 4;
            obj3.Name = "TestObj4";
            objLst.Add(obj3);
            //排序
            objLst.Sort();
            foreach(SortTestObj1 item in objLst)
            {
                Console.WriteLine("Code=" + item.Code + ",Name=" + item.Name);
            }
        }

        //Sort(IComparer(T))方法排序
        private static void LstComparerSort()
        {
            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);
            //按Code进行排序
            SortTestObj2Camparer codeCmp = new SortTestObj2Camparer(Obj2SortKind.Code);
            //排序
            objLst.Sort(codeCmp);
            Console.WriteLine("按Code排序的结果");
            foreach (SortTestObj2 item in objLst)
            {
                Console.WriteLine("Code=" + item.Code + ",Name=" + item.Name);
            }
            //按Name进行排序
            SortTestObj2Camparer nameCmp = new SortTestObj2Camparer(Obj2SortKind.Name);
            objLst.Sort(nameCmp);
            Console.WriteLine("按Name排序的结果");
            foreach (SortTestObj2 item in objLst)
            {
                Console.WriteLine("Code=" + item.Code + ",Name=" + item.Name);
            }
        }

        //Sort(Int32, Int32 IComparer(T))排序,指定List中排序的开始元素和终了元素
        private static void LstFromToSort()
        {
            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);
            //按Code进行排序
            SortTestObj2Camparer codeCmp = new SortTestObj2Camparer(Obj2SortKind.Code);
            //排序
            objLst.Sort(1, 3, codeCmp);
            Console.WriteLine("按Code排序的结果");
            foreach (SortTestObj2 item in objLst)
            {
                Console.WriteLine("Code=" + item.Code + ",Name=" + item.Name);
            }
            //按Name进行排序
            SortTestObj2Camparer nameCmp = new SortTestObj2Camparer(Obj2SortKind.Name);
            objLst.Sort(1, 3, nameCmp);
            Console.WriteLine("按Name排序的结果");
            foreach (SortTestObj2 item in objLst)
            {
                Console.WriteLine("Code=" + item.Code + ",Name=" + item.Name);
            }
        }

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

posted @ 2009-06-26 16:24  幽境仼孓  阅读(4521)  评论(0编辑  收藏  举报