GroupBy helps you organize items into groups based on a shared property. It makes it easy to see which items belong together.
When you want to count how many items share the same category.
When you want to list items grouped by a common feature, like all students by their grade.
When you want to summarize data by groups, like total sales per product.
When you want to separate a list into smaller lists based on a key.
Syntax
C Sharp (C#)
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.
Examples
Groups numbers into "Even" and "Odd" groups.
C Sharp (C#)
var numbers = newList<int> {1, 2, 3, 4, 5, 6};
var grouped = numbers.GroupBy(n => n % 2 == 0 ? "Even" : "Odd");
Groups words by their first letter.
C Sharp (C#)
var words = newList<string> {"apple", "banana", "apricot", "blueberry"};
var grouped = words.GroupBy(w => w[0]);
Sample Program
This program groups a list of fruits by their first letter and prints each group with its fruits.
C Sharp (C#)
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
staticvoid Main()
{
var fruits = newList<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}");
}
}
}
}
OutputSuccess
Important Notes
Groups are lazy-evaluated, so the grouping happens when you iterate over them.
You can use GroupBy with any property or computed key.
Summary
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.
Practice
(1/5)
1. What does the GroupBy method do in C#?
easy
A. It sorts elements in ascending order.
B. It groups elements of a collection based on a key selector.
C. It filters elements based on a condition.
D. It removes duplicate elements from a collection.
Solution
Step 1: Understand the purpose of GroupBy
The GroupBy method organizes elements by a key, creating groups of items sharing the same key.
Step 2: Compare with other operations
Sorting arranges order, filtering selects items, and removing duplicates eliminates repeats, which are different from grouping.
Final Answer:
It groups elements of a collection based on a key selector. -> Option B
Quick Check:
GroupBy = grouping by key [OK]
Hint: GroupBy always creates groups by a key, not sorting or filtering [OK]
Common Mistakes:
Confusing GroupBy with sorting methods
Thinking GroupBy filters items
Assuming GroupBy removes duplicates
2. Which of the following is the correct syntax to group a list of strings by their first character using LINQ in C#?
easy
A. var groups = list.GroupBy(s => s[0]);
B. var groups = list.GroupBy(s => s.Length);
C. var groups = list.GroupBy(s => s.ToUpper());
D. var groups = list.GroupBy(s => s.Substring(1));
Solution
Step 1: Identify grouping key for first character
Grouping by the first character means using s => s[0] as the key selector.
Step 2: Check other options
Grouping by length, uppercase string, or substring starting at index 1 does not group by first character.
Final Answer:
var groups = list.GroupBy(s => s[0]); -> Option A
Quick Check:
First char key = s[0] [OK]
Hint: Use s => s[0] to group by first character [OK]
Common Mistakes:
Using substring starting at 1 instead of 0
Grouping by string length instead of character
Using ToUpper() changes case but not grouping key
3. What is the output of the following C# code?
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)}");
}
medium
A. 1: 1
2: 2
3: 3
4: 4
5: 5
6: 6
B. Even: 2,4,6
Odd: 1,3,5
C. Odd: 1,3,5
Even: 2,4,6
D. Even: 1,3,5
Odd: 2,4,6
Solution
Step 1: Understand grouping key logic
Numbers are grouped by whether they are even or odd using the key "Even" or "Odd".
Step 2: Determine group contents and order
Group "Odd" contains 1,3,5; group "Even" contains 2,4,6. The foreach prints groups in order they appear, which is "Odd" then "Even".
Final Answer:
Odd: 1,3,5
Even: 2,4,6 -> Option C
Quick Check:
Group keys "Odd" then "Even" with correct items [OK]
Hint: GroupBy preserves order of first occurrence of keys [OK]
Common Mistakes:
Assuming groups print in alphabetical order
Mixing up even and odd groups
Expecting separate groups for each number
4. Identify the error in this C# code that tries to group words by their length:
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());
medium
A. Using group.ToString() instead of joining group elements.
B. GroupBy cannot be used on List<string>.
C. Missing semicolon after GroupBy statement.
D. word.Length is not a valid key selector.
Solution
Step 1: Check GroupBy usage
GroupBy on List<string> with word.Length is valid syntax and logic.
Step 2: Analyze output statement
Using group.ToString() prints the type name, not the grouped items. We should join group elements to display them.
Final Answer:
Using group.ToString() instead of joining group elements. -> Option A
Quick Check:
Print grouped items by joining, not ToString() [OK]
Hint: Join group elements to print, not group.ToString() [OK]
Common Mistakes:
Thinking GroupBy can't be used on lists
Forgetting to join group elements for display
Misunderstanding word.Length as key selector
5. Given a list of employees with properties Name and Department, how would you use GroupBy to create a dictionary where keys are departments and values are lists of employee names?
hard
A. var dict = employees.GroupBy(e => e.Name).ToDictionary(g => g.Key, g => g.Select(e => e.Department).ToList());
B. var dict = employees.ToDictionary(e => e.Department, e => e.Name);
C. var dict = employees.GroupBy(e => e.Department).ToList();
D. var dict = employees.GroupBy(e => e.Department).ToDictionary(g => g.Key, g => g.Select(e => e.Name).ToList());
Solution
Step 1: Group employees by Department
Use GroupBy with key selector e => e.Department to group employees by their department.
Step 2: Convert groups to dictionary with employee names list
Use ToDictionary with key as group.Key (department) and value as list of employee names using g.Select(e => e.Name).ToList().
Final Answer:
var dict = employees.GroupBy(e => e.Department).ToDictionary(g => g.Key, g => g.Select(e => e.Name).ToList()); -> Option D
Quick Check:
GroupBy + ToDictionary with Select names = correct [OK]
Hint: GroupBy then ToDictionary with Select for values list [OK]
Common Mistakes:
Using ToDictionary directly without grouping
Grouping by Name instead of Department
Not converting grouped items to list of names
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.