How do I order a Group result, in Linq?

泄露秘密 提交于 2019-12-18 10:33:31

问题


I have the following linq query, which works fine. I'm not sure how i order the group'd result.

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) }

the results are currently ordered by UserId ascending. I'm after Score descending.

thanks :)


回答1:


Just add the orderby clause ;-)

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 };



回答2:


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);

Hope this will fix your problem, easier than the top one ;)

Cheers



来源:https://stackoverflow.com/questions/755132/how-do-i-order-a-group-result-in-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!