2010-06-18 54 views
20
.OrderBy(y => y.Year).ThenBy(m => m.Month); 

如何設置descending命令?linq multiple order DESCENDING

編輯

我嘗試這樣做:

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) 
         ; 

,似乎工作。使用orderby兩次就像我在這裏使用的那樣是錯誤的嗎?

回答

44

您可以通過使用一對不同方法得到的降序排列:

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

使用LINQ查詢,你可以寫:

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

的技巧是,你只需要一個orderby條款 - 如果您添加多個這些列表,則列表將每次重新排序。要使用另一個鍵對第一個鍵相同的元素進行排序,您需要使用,orderby被翻譯爲OrderByOrderByDescending,而,被翻譯爲ThenByThenByDescending)將它們分開。

+0

很好,謝謝:)我編輯了我的問題,可否請你看看 – 2010-06-18 09:49:31