2010-05-04 70 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) };