简体   繁体   中英

OrderByDescending not working properly in Linq

I am using Linq and have the following code in 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. 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.

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

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

or do

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

OrderByDescending does not "sort in place". It rather returns an IOrderedEnumerable that you must assign to a variable.

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

OrderByDescending

doesn't order a list, it returns a new ordered IEnumerable . So use the result of OrderByDescending to display your items.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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