探討:如何使用委託,匿名方法對集合進行萬能排序

來源:互聯網
上載者:User

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

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.