探讨:如何使用委托,匿名方法对集合进行万能排序
下面Demo中我使用了2种排序方式
1.让Employee继承IComparable 接口,实现CompareTo方法排序
2.定义一个方法使用Comparison<T>委托,排序的操作交给匿名方法
看完下面的代码,你知道使用Comparison<T>委托的好处吗?
代码如下:
class Employee:IComparable
{
public string Name { get; set; }
public int Age { get; set; }
public static List<Employee> GetEmployees()
{
return new List<Employee>()
{
new Employee(){Name ="GuoHu",Age =25},
new Employee(){Name ="LeiHu",Age =23},
new Employee(){Name ="JunWenLi",Age =24},
new Employee(){Name ="JinHaoLiu",Age =25},
new Employee(){Name ="ChengFang",Age =24}
};
}
public int CompareTo(object obj)
{
Employee employee = obj as Employee;
if (employee != null)
{
return Name.CompareTo(employee.Name);
}
else
{
throw new ArgumentException("obj is not Employee");
}
}
}
class Test
{
static void SortAndShowFiles(string title, Comparison<Employee> employeeInfo)
{
List<Employee> employee = Employee.GetEmployees();
employee.Sort(employeeInfo);
Console.WriteLine(title);
foreach(Employee e in employee)
{
Console.WriteLine("Name:{0},Age:{1}", e.Name, e.Age);
}
}
static void Main()
{
List<Employee> employeeInfo = Employee.GetEmployees();
//Using IComparable sort
employeeInfo.Sort();
employeeInfo.ForEach(e => Console.WriteLine("Name:{0},Age{1}/t", e.Name, e.Age));
SortAndShowFiles("Sort by name", delegate(Employee e1, Employee e2) { return e1.Name.CompareTo(e2.Name); });
SortAndShowFiles("Sort by age", delegate(Employee e1, Employee e2) { return e1.Age.CompareTo(e2.Age); });
}
}