排序使用lambda / LINQ到对象列表 [英] Sorting a list using Lambda/Linq to objects

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

问题描述

我有一个字符串按属性排序的名字。我将需要使用波长/ LINQ到排序的对象列表。

例如:

 公共类Employee
{
  公共字符串名字{设置;得到;}
  公共字符串名字{设置;得到;}
  公众的DateTime DOB {集;得到;}
}
公共无效排序(参考表<员工>列表中,字符串sortBy,串sortDirection)
{
  //例数据:
  // sortBy =姓
  // sortDirection =ASC或DESC  VAR =排序列表。  如果(sortBy ==名字)
  {
    清单= list.OrderBy(X => x.FirstName).toList();
  }}


  1. 而不是使用一堆IFS的检查字段名(sortBy),有没有做排序
  2. 的更清洁的方式
  3. 是那种知道数据类型的?


解决方案

这是可以做到

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

.NET Framework是铸造的λ(EMP1,EMP2)=> INT 的Comparer<员工方式>

这有被强类型的优势。

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.

Ex:

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"

  var sort = list.

  if (sortBy == "FirstName")
  {
    list = list.OrderBy(x => x.FirstName).toList();    
  }

}

  1. Instead of using a bunch of ifs to check the fieldname (sortBy), is there a cleaner way of doing the sorting
  2. Is sort aware of datatype?

解决方案

This can be done as

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

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

This has the advantage of being strongly typed.

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

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