使用 Lambda/Linq to objects 对列表进行排序 [英] Sorting a list using Lambda/Linq to objects

查看:40
本文介绍了使用 Lambda/Linq to objects 对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the name of the "sort by property" in a string. I will need to use Lambda/Linq to sort the list of objects.

例如:

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();    
  }

}

  1. 不是使用一堆 if 来检查字段名 (sortBy),而是有一种更简洁的排序方式
  2. 排序是否知道数据类型?

推荐答案

可以这样做

list.Sort( (emp1,emp2)=>emp1.FirstName.CompareTo(emp2.FirstName) );

.NET 框架将 lambda (emp1,emp2)=>int 转换为 Comparer.

The .NET framework is casting the lambda (emp1,emp2)=>int as a Comparer<Employee>.

这具有强类型的优点.

如果需要降序/倒序,请反转参数.

If you need the descending/reverse order invert the parameters.

list.Sort( (emp1,emp2)=>emp2.FirstName.CompareTo(emp1.FirstName) );

这篇关于使用 Lambda/Linq to objects 对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆