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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With