委托匿名对集合万能排序 讨论:怎样使用委托,匿名方法对集合进行万能排序
人气:0想了解讨论:怎样使用委托,匿名方法对集合进行万能排序的相关内容吗,在本文为您仔细讲解委托匿名对集合万能排序的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:委托匿名,集合,万能排序,下面大家一起来学习吧。
下面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); });
}
}
加载全部内容