探讨:如何使用委托,匿名方法对集合进行万能排序
探讨:如何使用委托,匿名方法对集合进行万能排序
发布时间:2016-12-28 来源:查字典编辑
摘要:下面Demo中我使用了2种排序方式1.让Employee继承IComparable接口,实现CompareTo方法排序2.定义一个方法使用C...

下面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); });

}

}

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新C#教程学习
热门C#教程学习
编程开发子分类