How to use LINQ GroupBy in C#
The LINQ GroupBy() method organizes elements into groups based on a key selector. It returns an IEnumerable<IGrouping<TKey, TElement>> where each IGrouping holds the key and the matching elements.
Each group is itself an IEnumerable<T>, so you can apply further LINQ operations (Count, Sum, Average, etc.) to each group.
GroupBy() uses deferred execution. The grouping materializes when you iterate, call .ToList(), or perform an aggregation.
On this page
Basic GroupBy
Group Objects by Property
Count per Group
Aggregate Within Groups (Sum, Average, Max)
Group by Multiple Keys
Method Syntax vs Query Syntax
GroupBy vs ToLookup
Both group elements by a key, but they differ in when they execute and how you access the result.
GroupBy() | ToLookup() | |
|---|---|---|
| Execution | Deferred | Immediate |
| Access by key | Iterate groups | O(1) index lookup |
| Missing key | Skipped | Empty sequence returned |
| Use case | LINQ pipeline | Repeated lookups on same data |
Take It Further

The most comprehensive book covering C# 12 and .NET 8 from scratch to production.
C# 12 and .NET 8: Modern Cross-Platform Development · Mark J. Price
Get it on Amazon →As an Amazon Associate I earn from qualifying purchases.
Related Articles
Filter a collection in C# with LINQ Where() by passing a predicate function. Uses deferred execution and returns only elements satisfying the condition.
Use LINQ Select() in C# to project each element into a new form. Transforms a collection with a lambda and returns a new IEnumerable with the results.
Sort with LINQ OrderBy() in C# to get a new sorted sequence without modifying the original. Use ThenBy() for secondary sort keys.