- 我们在给List对象集合排序的时候,先要确定需要根据对象的哪个属性进行排序,然后在根据这个属性单独写一个排序类,继承IComparer接口,实现接口的Compare方法,在方法里面写排序逻辑,最后在集合调用Sort()方法排序的时候,将实例化排序类作为方法的参数
例子
- 排序类,继承IComparer接口,实现接口的Compare方法
using System.Collections.Generic;
namespace TestListSort
{
// 按照Id升序
public class PersonOrderBy_Id_ASC : IComparer<Person>
{
public int Compare(Person x, Person y)
{
return x.Id.CompareTo(y.Id);
}
}
}
using System.Collections.Generic;
namespace TestListSort
{
public class PersonOrderBy_Age_DESC : IComparer<Person>
{
public int Compare(Person x, Person y)
{
return y.Age.CompareTo(x.Age);
}
}
}
List<Person> persons = new List<Person>()
{
new Person{ Id = 3, Name = "大黄", Age = 30},
new Person{ Id = 1, Name = "郭靖", Age = 40},
new Person{ Id = 9, Name = "张三疯", Age = 23},
new Person{ Id = 5, Name = "小龙女", Age = 18}
};
// ----按照Id升序----
persons.Sort(new PersonOrderBy_Id_ASC());
persons.ForEach(delegate (Person person)
{
Console.WriteLine(string.Format("Id:{0}, Name:{1}, Age:{2}", person.Id, person.Name, person.Age));
});
// ----END按照Id升序---
Console.WriteLine("-------------------------------------------");
// ----按照年龄降序----
persons.Sort(new PersonOrderBy_Age_DESC());
persons.ForEach(delegate (Person person)
{
Console.WriteLine(string.Format("Id:{0}, Name:{1}, Age:{2}", person.Id, person.Name, person.Age));
});
// ----END按照年龄降序-----