码迷,mamicode.com
首页 > 编程语言 > 详细

比较和排序:IComparable和IComparer

时间:2016-08-02 11:31:47      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

创建实体类,如Person,默认按照年龄进行排序,则需要为实体类实现IComparable接口。

class Person : IComparable
{
     public string Name { get; set; }

     public int Age { get; set; }

     public override string ToString()
     {
          return string.Format("Name : {0} ; Age : {1} .", this.Name, this.Age);
     }

     public int CompareTo(object obj)
     {
           Person p = obj as Person;
           return this.Age.CompareTo(p.Age);
     }
}
static void Main(string[] args)
{

     List<Person> persons = new List<Person>();
     persons.Add(new Person() { Name = "ALin", Age = 13 });
     persons.Add(new Person() { Name = "John", Age = 34 });
     persons.Add(new Person() { Name = "Lee", Age = 26 });
     persons.Add(new Person() { Name = "Kui", Age = 47 });
     persons.Add(new Person() { Name = "Meimei", Age = 45 });
persons.Sort(); foreach (Person item in persons) { Console.WriteLine(item.ToString()); } Console.ReadKey(); }

执行结果:

技术分享

那么,问题来了。如果我们不想使用Age排序,或者Person的代码已经生成DLL等原因导致我们无法修改,现在要使用Name进行排序,这时IComparer的作用就来了。

可以使用IComparer实现一个比较器。

class SortByName : IComparer<Person>
{
      public int Compare(Person x, Person y)
      {
           return x.Name.CompareTo(y.Name);
      }
}  

在排序时为Sort方法提供此比较器

persons.Sort(new SortByName());

运行结果:

技术分享

比较和排序:IComparable和IComparer

标签:

原文地址:http://www.cnblogs.com/lideqiang/p/5728232.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!