• 我们在给List对象集合排序的时候,先要确定需要根据对象的哪个属性进行排序,然后在根据这个属性单独写一个排序类,继承IComparer接口,实现接口的Compare方法,在方法里面写排序逻辑,最后在集合调用Sort()方法排序的时候,将实例化排序类作为方法的参数

例子

  • 排序类,继承IComparer接口,实现接口的Compare方法
  1. using System.Collections.Generic;
  2. namespace TestListSort
  3. {
  4. // 按照Id升序
  5. public class PersonOrderBy_Id_ASC : IComparer<Person>
  6. {
  7. public int Compare(Person x, Person y)
  8. {
  9. return x.Id.CompareTo(y.Id);
  10. }
  11. }
  12. }
  13. using System.Collections.Generic;
  14. namespace TestListSort
  15. {
  16. public class PersonOrderBy_Age_DESC : IComparer<Person>
  17. {
  18. public int Compare(Person x, Person y)
  19. {
  20. return y.Age.CompareTo(x.Age);
  21. }
  22. }
  23. }
  • 使用
  1. List<Person> persons = new List<Person>()
  2. {
  3. new Person{ Id = 3, Name = "大黄", Age = 30},
  4. new Person{ Id = 1, Name = "郭靖", Age = 40},
  5. new Person{ Id = 9, Name = "张三疯", Age = 23},
  6. new Person{ Id = 5, Name = "小龙女", Age = 18}
  7. };
  8. // ----按照Id升序----
  9. persons.Sort(new PersonOrderBy_Id_ASC());
  10. persons.ForEach(delegate (Person person)
  11. {
  12. Console.WriteLine(string.Format("Id:{0}, Name:{1}, Age:{2}", person.Id, person.Name, person.Age));
  13. });
  14. // ----END按照Id升序---
  15. Console.WriteLine("-------------------------------------------");
  16. // ----按照年龄降序----
  17. persons.Sort(new PersonOrderBy_Age_DESC());
  18. persons.ForEach(delegate (Person person)
  19. {
  20. Console.WriteLine(string.Format("Id:{0}, Name:{1}, Age:{2}", person.Id, person.Name, person.Age));
  21. });
  22. // ----END按照年龄降序-----