Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I order a Group result, in Linq?

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

like image 705
Pure.Krome Avatar asked Apr 16 '09 07:04

Pure.Krome


People also ask

How do I sort by group in C#?

GroupBy(student => student.Name) . Select(group => new { Name = group. Key, Students = group. OrderByDescending(x => x.

Does LINQ GroupBy preserve order?

Found answer on MSDN: Yes.

What does LINQ GroupBy return?

A LINQ query can end with a GroupBy or Select clause. The result of GroupBy operators is a collection of groups. For example, GroupBy returns IEnumerable<IGrouping<TKey,Student>> from the Student collection: Return type of GroupBy()

How does GroupBy work LINQ?

GroupBy allows you to quickly group collections of related data by specific properties on your data. The grouped data is then arranged by sub-collections of items in those groups. Note: LINQ provides variants of each method in this article that work with either IEnumerable or IQueryable .


2 Answers

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 }; 
like image 187
Arjan Einbu Avatar answered Sep 21 '22 13:09

Arjan Einbu


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

like image 44
Prashant Cholachagudda Avatar answered Sep 22 '22 13:09

Prashant Cholachagudda