C# 比较和排序:IComparable和IComparer

创建实体类,如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());

运行结果:

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