How can I order multiple items using LINQ?

I have a collection, and I'm trying to take the "last" 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 fine, but I ran into a problem when I have an example in which there are two entries in MyCollection with the same start date. (so I assume this arbitrarily takes one of them?)

to deal with this situation, I want to add a check for this, so if there are several elements with the same starting point, they then go to another field to decide which one needs to be returned, but I do not want to have the expense of checking this second field if the situation does not exist.

+4
source share
4 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, item with last 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(); 
+12
source

you should find the extension ThenBy / ThenByDescending .

+1
source

If you use ThenBy() , it is always executed. The only way to execute "ThenBy" is only when the result from OrderBy is equal, you will need to write a custom IComparer .

+1
source

You may have support for your IComparable object, put your logic in it, and then just order the .OrderBy( a => a ) object .OrderBy( a => a )

(I think that works ... otherwise you could pass an object that implements IComparer for OrderBy)

0
source

All Articles