简体   繁体   English

OrderByDescending在Linq中无法正常工作

[英]OrderByDescending not working properly in Linq

I am using Linq and have the following code in C#: 我正在使用Linq并在C#中使用以下代码:

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

Basically I am trying to display list of annual and other leaves and I want to display them in DESCENDING order. 基本上我试图显示年度和其他叶子的列表,我想以DESCENDING顺序显示它们。 Problem is it always shows "Other Leaves" at the end of "Annual Leaves" no matter what. 问题是无论如何,它总是在“年叶”末尾显示“其他叶子”。 So basically it displays like this: 所以基本上它显示如下:

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

When in fact it should display like this: 实际上它应该显示如下:

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

Any idea why order by descending is not working? 任何想法为什么下降顺序不起作用?

EDIT 编辑

I am getting casting error when I use CONCAT. 当我使用CONCAT时,我得到了投射错误。

Both "Annual" and "Other" leaves are of same type but when I do “年度”和“其他”叶子都是相同类型,但是当我这样做时

leaves = leaves.Concat(otherleaves) 

then the project doesn't compile and gives error 然后项目不编译并给出错误

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

And if I do type cast: 如果我输入类型:

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

then I get runtime error. 然后我得到运行时错误。

You don't assign result of OrderByDescending 您没有指定OrderByDescending结果

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

or do 或者做

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

OrderByDescending does not "sort in place". OrderByDescending不会“排序”。 It rather returns an IOrderedEnumerable that you must assign to a variable. 它返回一个必须分配给变量的IOrderedEnumerable

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

OrderByDescending OrderByDescending

doesn't order a list, it returns a new ordered IEnumerable . 不排序列表,它返回一个新的有序IEnumerable So use the result of OrderByDescending to display your items. 因此,使用OrderByDescending 的结果来显示您的项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM