使用Lambda / Linq对对象排序列表

我在字符串中有“按属性排序”的名称。我将需要使用Lambda / Linq对对象列表进行排序。


例如:


public class Employee

{

  public string FirstName {set; get;}

  public string LastName {set; get;}

  public DateTime DOB {set; get;}

}



public void Sort(ref List<Employee> list, string sortBy, string sortDirection)

{

  //Example data:

  //sortBy = "FirstName"

  //sortDirection = "ASC" or "DESC"


  if (sortBy == "FirstName")

  {

    list = list.OrderBy(x => x.FirstName).toList();    

  }


}

与其使用大量的ifs来检查字段名(sortBy),还没有一种更干净的方式来进行排序

是否了解数据类型?


大话西游666
浏览 514回答 3
3回答

aluckdog

可以这样做list.Sort( (emp1,emp2)=>emp1.FirstName.CompareTo(emp2.FirstName) );.NET框架将lambda转换(emp1,emp2)=>int为Comparer<Employee>.这具有强类型输入的优势。

一只名叫tom的猫

您可以做的一件事就是更改,Sort以便更好地利用lambda。public enum SortDirection { Ascending, Descending }public void Sort<TKey>(ref List<Employee> list,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Func<Employee, TKey> sorter, SortDirection direction){&nbsp; if (direction == SortDirection.Ascending)&nbsp; &nbsp; list = list.OrderBy(sorter);&nbsp; else&nbsp; &nbsp; list = list.OrderByDescending(sorter);}现在,您可以指定在调用Sort方法时要排序的字段。Sort(ref employees, e => e.DOB, SortDirection.Descending);
打开App,查看更多内容
随时随地看视频慕课网APP