2010-06-18 40 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