LINQ Interview Question #59
What is GroupBy in LINQ?
Joins, Grouping, Set & Quantifier Operators Mid-Level Intermediate
Quick Interview Answer
GroupBy partitions a sequence into groups according to a key selector. Each resulting group has a Key and contains the elements associated with that key.
Detailed Explanation
GroupBy partitions a sequence into groups according to a key selector. Each resulting group has a Key and contains the elements associated with that key.
It is commonly used for summaries such as products by category, employees by department, or sales by year.
Code Example
var groups = products
.GroupBy(p => p.CategoryId);
foreach (var group in groups)
{
Console.WriteLine(group.Key);
foreach (var product in group)
Console.WriteLine(product.Name);
}