2012-08-30 75 views
3

晚上好,Linq按日期分組順序

我設法讓我的Linq查詢幾乎正確。還有一個問題我正在努力解決。

我的查詢是

var o = 
    (from c in x 
    group c by x.Date.Date into cc 
    select new 
    { 
     Group = cc.Key.Date, 
     Items = cc.ToList(), 
     ItemCount = cc.Count() 
    }).OrderByDescending(p => p.Group); 

現在這個查詢工作正常。它按日期在ListView內進行分組。 x.Date是我的SQL數據庫中的DateTime字段。因此,我選擇x.Date.Date作爲日期時間字段的實際日期,就好像它只是x.Date它將按日期和時間分組。

我的問題是,我如何按時間分組,使最新的時間在組的頂部?

非常感謝

回答

2

變化Items = cc.ToList()Items = cc.OrderBy(c => c.[field_you_want_to_sort_by]).ToList()

+0

非常感謝布歐,這工作完美。 – Nexiv

4

使用LINQ 「ThenBy()」 方法:

var o = (from c in x group c by x.Date.Date into cc select new 
    { 
    Group = cc.Key.Date, 
    Items = cc.OrderByDescending(y=>y.Date).ToList(), 
    ItemCount = cc.Count() 
    }) 
    .OrderByDescending(p => p.Group)  
+1

唯一的選擇,我可以在ThenBy選擇將p.Group ,p.Items和p.ItemCount – Nexiv

+0

已編輯; Items屬性可以在創建時排序。然後,你訂購這些團體。因此,按天排序的組按降序排序,然後組內的項目按日期*和時間降序排序。 – KeithS

1
var o = 
    (from c in x 
    group c by c.Date.Date into cc 
    select new 
    { 
     Group = cc.Key.Date, 
     Items = cc.OrderByDescending(a=>a.Date.Time).ToList(), 
     ItemCount = cc.Count() 
    }).OrderByDescending(p => p.Group);