当前位置: 编程技术>.net/c#/asp.net
探讨:如何使用委托,匿名方法对集合进行万能排序
来源: 互联网 发布时间:2014-10-22
本文导语: 下面Demo中我使用了2种排序方式1.让Employee继承IComparable 接口,实现CompareTo方法排序2.定义一个方法使用Comparison委托,排序的操作交给匿名方法 看完下面的代码,你知道使用Comparison委托的好处吗? 代码如下: class Employee:IComp...
下面Demo中我使用了2种排序方式
1.让Employee继承IComparable 接口,实现CompareTo方法排序
2.定义一个方法使用Comparison委托,排序的操作交给匿名方法
看完下面的代码,你知道使用Comparison委托的好处吗?
class Employee:IComparable
{
public string Name { get; set; }
public int Age { get; set; }
public static List GetEmployees()
{
return new List()
{
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 employeeInfo)
{
List 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 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); });
}
}
1.让Employee继承IComparable 接口,实现CompareTo方法排序
2.定义一个方法使用Comparison委托,排序的操作交给匿名方法
看完下面的代码,你知道使用Comparison委托的好处吗?
代码如下:
class Employee:IComparable
{
public string Name { get; set; }
public int Age { get; set; }
public static List GetEmployees()
{
return new List()
{
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 employeeInfo)
{
List 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 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); });
}
}