40

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

Pure.Krome
  • 84,693
  • 113
  • 396
  • 647

2 Answers2

65

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 };
Daniel Revell
  • 8,338
  • 14
  • 57
  • 95
Arjan Einbu
  • 13,543
  • 2
  • 56
  • 59
  • I tried just adding an orderby but it didn't work. But what you did was add a LET statement in there! Ahhh.. that's interesting... – Pure.Krome Apr 16 '09 at 11:57
  • I didn't check, but I don't think the LET is necessary, though. Will just "orderby g.Sum(x => x.Score)" be enough? – Arjan Einbu Apr 16 '09 at 12:54
  • could be, but then i have to have the g.Sum also listed in the select... so is that doing the sum, twice? – Pure.Krome Apr 16 '09 at 23:10
  • Hey Arjan, whats the difference between your query and query in another one, in terms of performance? which one is better to use in real time applications ? – Prashant Cholachagudda Apr 17 '09 at 04:56
  • I expect performance to be exactly the same. We're still just building the queries here. The query trees will look alike when you actually execute them. – Arjan Einbu Apr 17 '09 at 07:58
  • 2
    The "let" allows me to define the aggregate Before the orderby clause so that I can actually sort on it! Brilliant! How is this not common knowledge?! I will write all my linq queries like this from now on. Cool thing is, your approach supports MULTI-sort with various sort-directions. e.g. "orderby g.Key.UserId ascending, score descending" Suggestions to wrap the query by chaining OrderBy(), ThenBy(), and OrderByDescending() after it may result in multiple queries instead of one and look less like SQL. FYI: You can add more aggregates by adding another "let" statement below the first one! – MikeTeeVee Apr 12 '12 at 09:57
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);

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

Cheers

Prashant Cholachagudda
  • 13,012
  • 23
  • 97
  • 162