如何在Linq中订购组结果?

时间:2009-04-16 07:48:24

标签: linq sql-order-by group-by

我有以下linq查询,工作正常。我不确定我是如何订购小组的结果的。

from a in Audits
join u in Users on a.UserId equals u.UserId
group a by a.UserId into g
select new { UserId = g.Key, Score = g.Sum(x => x.Score) }

结果目前按UserId升序排序。我在分数下降之后。

谢谢:)

2 个答案:

答案 0 :(得分:65)

只需添加orderby子句; - )

from a in Audits
join u in Users on a.UserId equals u.UserId
group a by a.UserId into g
let score = g.Sum(x => x.Score)
orderby score descending
select new { UserId = g.Key, Score = score };

答案 1 :(得分:13)

var results =
 (from a in Audits
join u in Users on a.UserId equals u.UserId
group a by a.UserId into g
select new { UserId = g.Key, Score = g.Sum(x => x.Score) })
.OrderByDescending(p=>p.Score);

希望这能解决你的问题,比最上层更容易;)

干杯