Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering and subordering a list using a lambda

Tags:

c#

lambda

I need to order a list by status == "Rejected" and date ascending and then by status == "Accepted" and date descending.

I am trying the following but I'm not sure how to go about this:

items
   .OrderBy(x => x.status == "Rejected") 
   .ThenBy(x => x.DateSubmitted)
   .ThenBy(x => x.status == "Accepted") 
   .ThenByDescending(x => x.DateSubmitted)
like image 766
user895400 Avatar asked Aug 13 '26 21:08

user895400


1 Answers

You're describing the task a bit awkward, which (I think) leads you to a slightly wrong implementation.

I say:

items
   .Where(x => x.status == "Rejected") 
   .OrderBy(x => x.DateSubmitted)
   .Concat(items.
       .Where(x => x.status == "Accepted") 
       .OrderByDescending(x => x.DateSubmitted));

The main difference is that now, status other than "Rejected" or "Accepted" are not shown. However, I think it is what you intended. If you want the full set, consider using

items
   .Where(x => x.status == "Rejected") 
   .OrderBy(x => x.DateSubmitted)
   .Concat(items.
       .Where(x => x.status != "Rejected") 
       .OrderByDescending(x => x.DateSubmitted));

PS. This is also assuming Linq-To-Objects. I'm not very well-versed with Linq-to-EF or Linq-to-SQL

like image 179
sehe Avatar answered Aug 15 '26 09:08

sehe