2010-05-04 82 views
1

如何將linq中「group ... by ... into ...」語句的結果排序? 例如:如何與Linq訂購一組結果?

var queryResult = from records in container.tableWhatever 
        where records.Time >= DateTime.Today 
        group records by tableWhatever.tableHeader.UserId into userRecords 
        select new { UserID = userRecords.Key, Records = userRecords }; 

查詢返回由 「userid」 分組表 「contain.tableWhatever」 的記載。我希望每個組中的返回結果都是按照時間順序排列的。我怎樣才能做到這一點?

更具體的,假設上述查詢返回只有一組這樣的:

{UserID = 1, Records= {name1 5/3/2010_7:10pm; 
         name2 5/3/2010_8:10pm; 
         name3 5/3/2010_9:10pm} } 

插在上面的查詢的排序依據語句後,返回的結果應該是這樣的:

{UserID = 1, Records= {name3 5/3/2010_9:10pm; 
         name2 5/3/2010_8:10pm; 
         name1 5/3/2010_7:10pm} } 

感謝您的幫助!

回答

2

只需使用OrderByDescending擴展的匿名類型訂購的記錄。

var queryResult = from records in container.tableWhatever 
        where records.Time >= DateTime.Today 
        group records by tableWhatever.tableHeader.UserId into userRecords 
        select new 
        { 
         UserID = userRecords.Key, 
         Records = userRecords.OrderByDescending(u => u.Time) 
        }; 
+0

非常感謝。有用。 – Aaron 2010-05-04 16:26:29

0

可以這樣做:

var queryResult = from records in container.tableWhatever 
       where records.Time >= DateTime.Today 
       group records by tableWhatever.tableHeader.UserId into userRecords 
       select new { UserID = userRecords.Key, Records = userRecords.OrderByDescending(r=>r.Time) };