LINQ Interview Question #139
How can LINQ return the top N records per group?
Advanced LINQ, Practical Problems & Senior Interview Scenarios Senior Advanced
Quick Interview Answer
A common LINQ-to-Objects pattern groups records, orders each group, and takes the required number from each group using SelectMany.
Detailed Explanation
A common LINQ-to-Objects pattern groups records, orders each group, and takes the required number from each group using SelectMany.
For IQueryable database queries, translation support for top-N-per-group shapes depends on the provider and query form. Performance-sensitive cases should inspect generated SQL.
Code Example
var topTwoPerCategory = products
.GroupBy(p => p.CategoryId)
.SelectMany(g => g
.OrderByDescending(p => p.Price)
.Take(2));