How to Use LINQ GroupBy in C# - Simple Guide
Use
GroupBy in LINQ to group elements of a collection by a key selector function. It returns groups as IGrouping<TKey, TElement> which you can iterate to access grouped items. This helps organize data by categories or properties easily.Syntax
The basic syntax of GroupBy in LINQ is:
source.GroupBy(keySelector)groups elements by a key.keySelectoris a function that selects the key to group by.- The result is a collection of
IGrouping<TKey, TElement>where each group has a key and elements.
csharp
var grouped = collection.GroupBy(item => item.KeyProperty);Example
This example groups a list of words by their first letter and prints each group with its items.
csharp
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { List<string> words = new List<string> { "apple", "apricot", "banana", "blueberry", "cherry" }; var groupedWords = words.GroupBy(word => word[0]); foreach (var group in groupedWords) { Console.WriteLine($"Words that start with '{group.Key}':"); foreach (var word in group) { Console.WriteLine($" {word}"); } } } }
Output
Words that start with 'a':
apple
apricot
Words that start with 'b':
banana
blueberry
Words that start with 'c':
cherry
Common Pitfalls
Common mistakes when using GroupBy include:
- Not realizing
GroupByreturns groups, not a flat list. - Forgetting to iterate over groups and their elements separately.
- Using a key selector that returns non-unique or unexpected keys.
- Assuming groups are sorted;
GroupBydoes not guarantee order.
Always check the key selector logic and iterate groups properly.
csharp
/* Wrong: Trying to treat GroupBy result as a flat list */ var wrong = words.GroupBy(w => w[0]).ToList(); // wrong is a list of groups, not strings /* Right: Iterate groups and then items */ foreach (var group in words.GroupBy(w => w[0])) { Console.WriteLine(group.Key); foreach (var item in group) { Console.WriteLine(item); } }
Quick Reference
Tips for using GroupBy effectively:
- Use a clear key selector function.
- Remember the result is groups, each with a
Keyand elements. - Use
ToDictionaryif you want a dictionary from groups. - Combine with
OrderByto sort groups or elements.
Key Takeaways
Use GroupBy with a key selector to group collection elements by a property.
GroupBy returns groups with a Key and a collection of elements, not a flat list.
Always iterate groups and their elements separately to access data.
GroupBy does not sort groups; use OrderBy if sorting is needed.
Check your key selector carefully to avoid unexpected grouping.