探讨:如何使用委托,匿名方法对集合进行万能排序
程序员文章站
2024-02-13 11:08:22
下面demo中我使用了2种排序方式1.让employee继承icomparable 接口,实现compareto方法排序2.定义一个方法使用comparison
下面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); });
}
}
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); });
}
}