OrderByDescending在Linq中无法正常工作

时间:2014-02-12 11:13:36

标签: c# linq

我正在使用Linq并在C#中使用以下代码:

leaves = GetAnnualLeaves();
otherleaves = GetOtherLeaves();
leaves.AddRange(otherleaves);
leaves.OrderByDescending(e => e.StartDate);

基本上我正在尝试显示年度和其他叶子的列表,我想以DESCENDING顺序显示它们。问题是无论如何,它总是在“年叶”末尾显示“其他叶子”。所以基本上它显示如下:

2013-06-29 Annual
2012-01-01 Annual
2011-05-02 Annual
2013-05-01 Other

实际上它应该显示如下:

2013-06-29 Annual
2013-05-01 Other
2012-01-01 Annual
2011-05-02 Annual

任何想法为什么按降序排序都不起作用?

编辑

使用CONCAT时出现转换错误。

“年度”和“其他”叶子的类型相同,但是当我这样做时

leaves = leaves.Concat(otherleaves) 

然后项目不编译并给出错误

Cannot implicitly convert type System.Collections.Generic.IEnumerable<MyEntity> to System.Collections.Generic.List<MyEntity>

如果我输入演员:

leaves = (List<MyEntity>)leaves.Concat(otherleaves)

然后我得到运行时错误。

3 个答案:

答案 0 :(得分:9)

您未指定OrderByDescending

的结果
leaves = leaves.OrderByDescending(e => e.StartDate).ToList();

或做

leaves = leaves.Concat(otherleaves).OrderByDescending(e => e.StartDate).ToList();

答案 1 :(得分:1)

OrderByDescending没有“排序”。它返回一个必须分配给变量的IOrderedEnumerable

var orderedLeaves = leaves.OrderByDescending(e => e.StartDate);

答案 2 :(得分:0)

  

OrderByDescending

没有订购列表,它返回一个新的有序IEnumerable。因此,使用OrderByDescending结果来显示您的商品。

相关问题