GroupBy operation in C Sharp (C#) - Time & Space Complexity
When we use GroupBy, we want to organize items by a key. Understanding how long this takes helps us write faster programs.
We ask: How does the time to group items grow as the list gets bigger?
Analyze the time complexity of the following code snippet.
var numbers = new List {1, 2, 3, 4, 5, 6};
var groups = numbers.GroupBy(n => n % 2);
foreach (var group in groups)
{
Console.WriteLine($"Key: {group.Key}");
foreach (var num in group)
{
Console.WriteLine(num);
}
}
This code groups numbers by whether they are even or odd, then prints each group.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: One pass through the list to assign each item to a group.
- How many times: Once for each item in the list (n times).
As the list grows, the time to group items grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 operations |
| 100 | About 100 operations |
| 1000 | About 1000 operations |
Pattern observation: Doubling the input roughly doubles the work done.
Time Complexity: O(n)
This means the time to group items grows in a straight line with the number of items.
[X] Wrong: "GroupBy takes longer than just looking at each item once because it does extra work for each group."
[OK] Correct: GroupBy still only looks at each item once; it just organizes them as it goes, so the main work grows linearly with the list size.
Knowing how grouping scales helps you explain your code choices clearly and shows you understand how data size affects performance.
"What if we nested GroupBy inside another GroupBy? How would the time complexity change?"