Sort排序浅聊

集合是什么?笔者简易描述:数组是不可变的,所以我们使用集合来代替。

using.System.Collections; 非泛型集合

using.System.Collections.Gernerc;泛型集合

我们现在创建一个集合,并对其排序~

            ArrayList arr1 = new ArrayList() { 2, 1, 5, 4, 10, 9 };
            arr1.Sort();
       foreach (int i in arr1)
            {
                Console.WriteLine(i);
            }

倒叙,我去,想要升序可以Reverse()翻转下

现在我申明了一个类 Person,字段Name以及Age

           ArrayList arr2 = new ArrayList() { 
new Person(){Name="Tom",Age=18}, new Person(){Name="Chris",Age=20}, new Person(){Name="James",Age=19}, new Person (){Name="Alice",Age=10} }; arr2.Sort();

 

排序的时候发现报错了,日了狗。(编译通过,但是运行出错)

打开错误详情

异常详情:{"必须至少有一个对象实现 IComparable。"}

出错原因:没有给对象指定一个标准来判定比较
就好比你告诉班长(C#)对整个班级进行大小排序,班长会无法执行,为什么呢?因为班里面的人(对象)可以比较年龄、身高、体重等等,所以班长不知道你到底需要比较什么?
所以我们需要实现 IComparable 接口来实现对一个标准进行比较
   class Person:IComparable        
    {
        private string _name;
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

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

        public int CompareTo(object obj)
        {
            Person p = obj as Person;
            if (p != null)
            {
                return this.Age- p.Age;//或者比较Name长度,this.Name.Length 
            }
            else
            {
                throw new ArgumentException();
            }
        }

Get:

    

 

如果两个人的年龄一样呢?

   

 

为什么Chirs在前面呢?难道又比较了Name的ASCII,这么智能?笔者认为是因为Chirs申明在前的缘故

那我把 Chirs 和 James 换个位置试试看

  果然如此

 

这一步骤具体是如何实现的呢?笔者还没有彻底想通,233

 

那么我们在继续想,能否实现想比较姓名大小、年龄大小等,这些大小都可以比较,根据我选择不同来实现呢?

在Sort方法的重载里可以具体实现比较器 IComparer ,通过传入不同比较器来实现不同比较方式

class Person       
    {
        private string _name;
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        private int _age;
        public int Age
        {
            get { return _age; }
            set { _age = value; }
        }
}
  
   //升序
class PersonSortByAgeAsc : IComparer { public int Compare(object x, object y) { Person p1 = x as Person; Person p2 = y as Person; if (p1 != null && p2 != null) { return p1.Age - p2.Age; } else { throw new ArgumentException(); } } }

arr2.Sort(new PersonSortByAgeAsc());

 

    /// <summary>
    /// 降序
    /// </summary>
    class PersonSortByAgeDesc : IComparer
    {
        public int Compare(object x, object y)
        {
            Person p1 = x as Person;
            Person p2 = y as Person;
            if (p1 != null && p2 != null)
            {
                return p2.Age - p1.Age;
            }
            else
            {
                throw new ArgumentException();
            }
        }
    }

 arr.Sort(new PersonSortByAgeDesc());   //传入的参数不同, 比较方式不同,更加灵活多变,代码可塑性强!


让班长排序,我们直接提供了一台机器,这台机器即可根据自定义来选择排序方式(多态)

 

posted on 2015-07-09 21:21  哥不寂寞  阅读(248)  评论(0编辑  收藏  举报

导航