How do I order a Group result, in Linq?

Pure.Krome picture Pure.Krome · Apr 16, 2009 · Viewed 39.3k times · Source

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

Answer

Arjan Einbu picture Arjan Einbu · Apr 16, 2009

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