Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I order by multiple Items using LINQ?

I have a collection and i am trying to take the "latest" item in the collection based on the following code:

 return MyCollection.OrderByDescending(a => a.StartDate).FirstOrDefault(a => a.StartDate.Date <= DateTime.UtcNow.Date));

This works great but I ran into an issue where I have an example where there are two entries in the MyCollection with the same start date. (so i assume it arbitrary takes one of them ??)

to deal with this situation, i want to add a check for this so if there are multiple items with the same startdate, it then goes to another field to decide which one to return but i don't want to have the expense of checking this second field unless the situation exists.

like image 285
leora Avatar asked Dec 10 '22 07:12

leora


1 Answers

use ThenBy() or ThenByDescending()

return MyCollection.OrderByDescending(a => a.StartDate).ThenBy(a=>a.Fish).FirstOrDefault(a => a.StartDate <= DateTime.UtcNow.Date));

As you want the item with the latest date....

var max=MyCollection.Where(a => a.StartDate.Date <= DateTime.UtcNow.Date).Max(a=>a.StartDate);
result=MyCollection.Where(a=>a.StartDate == max).OrderBy(a=>a.SecondProp).First();
like image 126
Bob Vale Avatar answered Jan 02 '23 20:01

Bob Vale