如何从linq中的“group ... by ... into ...”语句中订购结果? 例如:
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”分组的表“contains.tableWhatever”中的记录。我希望每个组中的返回结果按时间降序排序。我怎么能这样做?
更具体地说,假设上面的查询只返回一个如下所示的组:
{UserID = 1, Records= {name1 5/3/2010_7:10pm;
name2 5/3/2010_8:10pm;
name3 5/3/2010_9:10pm} }
在上面的查询中插入orderby语句后,返回的结果应如下所示:
{UserID = 1, Records= {name3 5/3/2010_9:10pm;
name2 5/3/2010_8:10pm;
name1 5/3/2010_7:10pm} }
感谢您的帮助!
答案 0 :(得分: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 )
};
答案 1 :(得分: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) };