LINQ to SQL group by with take

Taho picture Taho · Sep 3, 2010 · Viewed 7.7k times · Source

I have a table that looks like this:

Id GroupId Value

and it has about 100 rows

How can I return the top 10 rows for value but with no duplicating GroupId?

Answer

Kirk Woll picture Kirk Woll · Sep 3, 2010

This should do it:

var results = table
    .GroupBy(x => x.GroupId)
    .Select(x => new { Row = x, Value = x.Max(y => y.Value) })
    .OrderByDescending(x => x.Value)
    .Select(x => x.Row)
    .Take(10);

Edit: Modified to return the entire object.