Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LInq Order By and Order By Desc

I am using "Linq" to filter list of objects and to sort them, like

myList.Where(x => x.Item!= "SF" && x.AdSize == minadSize)
      .OrderBy(x => x.ManufacturingDate)
      .OrderBy(x=>x.ExpiryDate);

I doubt whether i am doing it right or not that is if i want to "sorting" on multiple fields then is it necessary to use multiple Order By clause cant it be done with single "OrderBy"

like image 307
Deepesh Avatar asked Jun 10 '11 11:06

Deepesh


People also ask

How to do Order By descending in LINQ?

OrderByDescending Operator If you want to rearrange or sort the elements of the given sequence or collection in descending order in query syntax, then use descending keyword as shown in below example. And in method syntax, use OrderByDescending () method to sort the elements of the given sequence or collection.

How do I sort multiple columns in LINQ?

Orderby(x=>x. Columnname). Orderby(x=>x. Columnname) and think that will do the ordering in multiple columns.

How does OrderBy and ThenBy work?

Generally, ThenBy method is used with the OrderBy method. The OrderBy() Method, first sort the elements of the sequence or collection in ascending order after that ThenBy() method is used to again sort the result of OrderBy() method in ascending order.


1 Answers

Don't use multiple OrderBy calls - use OrderBy followed by ThenBy:

var query = myList.Where(x => x.Item!= "SF" && x.AdSize == minadSize)
                  .OrderBy(x => x.ManufacturingDate)
                  .ThenBy(x => x.ExpiryDate); // Could add more ThenBy calls

If you use OrderBy twice, it will reorder the already-ordered-by-date list by expiry-date, whereas I assume you only want to order by expiry date for items with an equal manufacturing date, which is what the above does.

Obviously there's a ThenByDescending method too. For example:

var query = people.OrderBy(x => x.LastName)
                  .ThenBy(x => x.FirstName)
                  .ThenByDescending(x => x.Age)
                  .ThenBy(x => x.SocialSecurity);
like image 125
Jon Skeet Avatar answered Jan 02 '23 20:01

Jon Skeet