views:

2125

answers:

4

Hi folks,
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 :)

+16  A: 

Just add the orderby clause ;-)

Here's how:

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 };
Arjan Einbu
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
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
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
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
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
+3  A: 
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
A: 

It just keeps getting better - thanks to this thread I was able to clean up the DetailGroups query using a join - kinda doubtful about how it was written before with the nested from and the where. I learned so much from working on this I'm posting the Nexted ListViews and OnItemDatabound that goes with it, so just skip the rest if the code in my previous post is not of interest.

I ended up not posting, couldn't get the formatting right. If you're interested let me know and I'll email it to you or try again.

A: 

perfeito funcionou