[英]OrderByDescending not working properly in 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)
然后我得到运行时错误。
您没有指定OrderByDescending
结果
leaves = leaves.OrderByDescending(e => e.StartDate).ToList();
或者做
leaves = leaves.Concat(otherleaves).OrderByDescending(e => e.StartDate).ToList();
OrderByDescending
不会“排序”。 它返回一个必须分配给变量的IOrderedEnumerable
。
var orderedLeaves = leaves.OrderByDescending(e => e.StartDate);
OrderByDescending
不排序列表,它返回一个新的有序IEnumerable
。 因此,使用OrderByDescending
的结果来显示您的项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.