Introduction
GroupBy helps you organize items into groups based on a shared property. It makes it easy to see which items belong together.
Jump into concepts and practice - no test required
GroupBy helps you organize items into groups based on a shared property. It makes it easy to see which items belong together.
var grouped = collection.GroupBy(item => item.KeyProperty);
GroupBy returns groups as IGrouping<TKey, TElement> collections.
You access each group's key with group.Key and its items by iterating over the group.
var numbers = new List<int> {1, 2, 3, 4, 5, 6}; var grouped = numbers.GroupBy(n => n % 2 == 0 ? "Even" : "Odd");
var words = new List<string> {"apple", "banana", "apricot", "blueberry"}; var grouped = words.GroupBy(w => w[0]);
This program groups a list of fruits by their first letter and prints each group with its fruits.
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { var fruits = new List<string> { "apple", "banana", "apricot", "blueberry", "avocado" }; var groupedFruits = fruits.GroupBy(f => f[0]); foreach (var group in groupedFruits) { Console.WriteLine($"Fruits starting with '{group.Key}':"); foreach (var fruit in group) { Console.WriteLine($" - {fruit}"); } } } }
Groups are lazy-evaluated, so the grouping happens when you iterate over them.
You can use GroupBy with any property or computed key.
GroupBy organizes items into groups by a key.
You get a collection of groups, each with a key and items.
It helps summarize or categorize data easily.
GroupBy method do in C#?s => s[0] as the key selector.var numbers = new[] {1, 2, 3, 4, 5, 6};
var groups = numbers.GroupBy(n => n % 2 == 0 ? "Even" : "Odd");
foreach (var group in groups) {
Console.WriteLine($"{group.Key}: {string.Join(",", group)}");
}var words = new List<string> {"apple", "bat", "car", "dog"};
var groups = words.GroupBy(word => word.Length);
foreach (var group in groups)
Console.WriteLine(group.Key + ": " + group.ToString());Name and Department, how would you use GroupBy to create a dictionary where keys are departments and values are lists of employee names?e => e.Department to group employees by their department.g.Select(e => e.Name).ToList().