C# 中list的排序

将list中的元素按照某种规则排序是件很平常的事,今天在网上搜了下,竟然没有好的解决方法。

后来发现list本身含sort方法,并支持自定义排序规则。

现有类A,含三个属性,分别是NO,AGE,NAME,现在要求按照这个顺序排序(既先比较NO,如果相同比较AGE,如果AGE相同就比较NAME)。

类A的代码:

类A
class A
    {
        
private string _name;
        
public string NAME
        {
            
get { return _name; }
            
set { _name = value; }
        }

        
private int _age;
        
public int AGE
        {
            
get { return _age; }
            
set { _age = value; }
        }

        
private int _no;
        
public int NO
        {
            
get { return _no; }
            
set { _no = value; }
        }

        
public A(int no, int age, string name)
        {
            
this.NO = no;
            
this.AGE = age;
            
this.NAME = name;
        }
    }

先定义排序规则:

代码:排序规则
        private static int SortA(A a1, A a2)
        {
            
if (a1.NO.CompareTo(a2.NO) != 0)
                
return a1.NO.CompareTo(a2.NO);
            
else if (a1.AGE.CompareTo(a2.AGE) != 0)
                
return a1.AGE.CompareTo(a2.AGE);
            
else
                
return a1.NAME.CompareTo(a2.NAME);
        }

测试排序规则:

代码:测试排序
        static void Main(string[] args)
        {
            List
<A> list = new List<A>();
            list.Add(
new A(2020"00001"));
            list.Add(
new A(1850"00003"));
            list.Add(
new A(2019"00004"));
            list.Add(
new A(2121"00005"));
            list.Add(
new A(1919"00006"));
            list.Add(
new A(9919"00007"));
            list.Add(
new A(1919"00008"));
            list.Add(
new A(3850"00009"));

            list.Sort(SortA);

            
foreach (A a in list)
            {
                Console.WriteLine(a.NO 
+ " " + a.AGE + " " + a.NAME);
            }

            Console.ReadLine();
        }

输出结果正常,证明方法有效.

注意,上面测试代码调用很简单,就是list.Sort(SortA); 就可以了。

其实这是用委托表示的方法对 List 的元素进行排序。内部实现则为QuickSort 算法。

 

详情可参考:http://msdn.microsoft.com/zh-cn/library/w56d4y5z(VS.80).aspx

原文地址:https://www.cnblogs.com/liaozh/p/1619679.html