Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linq multiple order DESCENDING

Tags:

.OrderBy(y => y.Year).ThenBy(m => m.Month); 

How to set descending order?

EDIT:

I tried this:

var result = (from dn in db.DealNotes                          where dn.DealID == dealID                                                   group dn by new { month = dn.Date.Month, year = dn.Date.Year } into date                          orderby date.Key.year descending                          orderby date.Key.month descending                          select new DealNoteDateListView {                               DisplayDate = date.Key.month + "-" + date.Key.year,                              Month = date.Key.month,                              Year = date.Key.year,                              Count = date.Count()                          })                          //.OrderBy(y => y.Year).ThenBy(m => m.Month)                          ; 

And it seems working. Is it wrong to use orderby twice like I used it here?

like image 755
ilija veselica Avatar asked Jun 18 '10 09:06

ilija veselica


People also ask

How to sort in descending order in linq?

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 order by two columns in Linq?

Always make use of ThenBy() after OrderBy() because OrderBy() returns an IOrderedEnumerable which then exposes the methods ThenBy() and ThenByDescending() . This means that we can OrderBy on multiple fields by chaining OrderBy() and ThenBy() together.

What is OrderByDescending?

OrderByDescending<TSource,TKey>(IEnumerable<TSource>, Func<TSource,TKey>) Sorts the elements of a sequence in descending order according to a key.


1 Answers

You can get the descending ordering by using a different pair of methods:

items.OrderByDescending(y => y.Year).ThenByDescending(m => m.Month);  

Using LINQ query, you can write:

from date in db.Dates orderby date.Key.year descending, date.Key.month descending  select new { ... }  

The trick is that you need only one orderby clause - if you add multiple of these, the list will be re-sorted each time. To sort elements that have the first key equal using another key, you need to separate them using , (orderby is translated to OrderBy or OrderByDescending while , is translated to ThenBy or ThenByDescending).

like image 96
Tomas Petricek Avatar answered Sep 22 '22 15:09

Tomas Petricek