Bird
Raised Fist0
C Sharp (C#)programming~20 mins

GroupBy operation in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
GroupBy Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of GroupBy with simple key selector
What is the output of this C# code snippet that groups numbers by their remainder when divided by 3?
C Sharp (C#)
using System;
using System.Linq;

class Program {
    static void Main() {
        var numbers = new[] {1, 2, 3, 4, 5, 6};
        var groups = numbers.GroupBy(n => n % 3);
        foreach (var group in groups) {
            Console.WriteLine($"Key: {group.Key}, Values: {string.Join(",", group)}");
        }
    }
}
A
Key: 0, Values: 3,6
Key: 1, Values: 1,4
Key: 2, Values: 2,5
B
Key: 3, Values: 3,6
Key: 1, Values: 1,4
Key: 2, Values: 2,5
C
Key: 1, Values: 1,4
Key: 2, Values: 2,5
Key: 0, Values: 3,6
D
Key: 0, Values: 6,3
Key: 1, Values: 4,1
Key: 2, Values: 5,2
Attempts:
2 left
💡 Hint
Remember that GroupBy preserves the order of groups as they first appear in the source.
Predict Output
intermediate
2:00remaining
GroupBy with complex key and projection
What is the output of this C# code that groups words by their first letter and selects the count of words in each group?
C Sharp (C#)
using System;
using System.Linq;

class Program {
    static void Main() {
        string[] words = {"apple", "apricot", "banana", "blueberry", "cherry"};
        var result = words.GroupBy(w => w[0])
                          .Select(g => new { Letter = g.Key, Count = g.Count() });
        foreach (var item in result) {
            Console.WriteLine($"{item.Letter}: {item.Count}");
        }
    }
}
A
a: 2
b: 2
c: 1
B
a: 2
b: 1
c: 2
C
a: 1
b: 2
c: 2
D
a: 2
b: 2
c: 2
Attempts:
2 left
💡 Hint
Count how many words start with each letter.
🔧 Debug
advanced
2:00remaining
Identify the error in GroupBy usage
What error does this C# code produce when run?
C Sharp (C#)
using System;
using System.Linq;

class Program {
    static void Main() {
        var data = new[] {1, 2, 3, 4};
        var groups = data.GroupBy(n => n > 2 ? "High" : "Low");
        foreach (var group in groups) {
            Console.WriteLine(group.Key + ": " + group);
        }
    }
}
ASystem.InvalidOperationException at runtime
B
Output:
Low: System.Linq.Lookup`2+Grouping
High: System.Linq.Lookup`2+Grouping
CCompile-time error: Cannot convert from 'System.Linq.IGrouping<string,int>' to 'string'
D
Output:
Low: 1,2
High: 3,4
Attempts:
2 left
💡 Hint
Check what happens when you print a group object directly.
Predict Output
advanced
2:00remaining
GroupBy with ordering inside groups
What is the output of this C# code that groups people by age and orders names inside each group alphabetically?
C Sharp (C#)
using System;
using System.Linq;
using System.Collections.Generic;

class Person {
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program {
    static void Main() {
        var people = new List<Person> {
            new Person { Name = "John", Age = 30 },
            new Person { Name = "Jane", Age = 25 },
            new Person { Name = "Jake", Age = 30 },
            new Person { Name = "Jill", Age = 25 }
        };

        var groups = people.GroupBy(p => p.Age)
                           .Select(g => new {
                               Age = g.Key,
                               Names = g.OrderBy(p => p.Name).Select(p => p.Name)
                           });

        foreach (var group in groups) {
            Console.WriteLine($"Age: {group.Age}, Names: {string.Join(",", group.Names)}");
        }
    }
}
A
Age: 30, Names: Jake,John
Age: 25, Names: Jane,Jill
B
Age: 25, Names: Jill,Jane
Age: 30, Names: John,Jake
C
Age: 25, Names: Jane,Jill
Age: 30, Names: Jake,John
D
Age: 30, Names: John,Jake
Age: 25, Names: Jill,Jane
Attempts:
2 left
💡 Hint
Groups are ordered by first occurrence of keys, and names inside groups are alphabetically ordered.
Predict Output
expert
3:00remaining
GroupBy with nested grouping and flattening
What is the output of this C# code that groups numbers by even/odd, then groups each group by remainder mod 3, and finally flattens the results?
C Sharp (C#)
using System;
using System.Linq;

class Program {
    static void Main() {
        var numbers = Enumerable.Range(1, 6);
        var nestedGroups = numbers.GroupBy(n => n % 2 == 0 ? "Even" : "Odd")
                                  .Select(g => new {
                                      Parity = g.Key,
                                      SubGroups = g.GroupBy(x => x % 3)
                                  });

        foreach (var group in nestedGroups) {
            Console.WriteLine(group.Parity + ":");
            foreach (var subGroup in group.SubGroups) {
                Console.WriteLine($"  Remainder {subGroup.Key}: {string.Join(",", subGroup)}");
            }
        }
    }
}
A
2 :2 redniameR  
4 :1 redniameR  
6 :0 redniameR  
:nevE
 :2 redniameR  
3 :0 redniameR  
5,1 :1 redniameR  
:ddO
B
Odd:
  Remainder 1: 1,4
  Remainder 0: 3
  Remainder 2: 5
Even:
  Remainder 2: 2,5
  Remainder 0: 6
  Remainder 1: 4
C
Odd:
  Remainder 1: 1,5
  Remainder 0: 3
  Remainder 2: 
Even:
  Remainder 0: 6
  Remainder 1: 4
  Remainder 2: 2
D
Odd:
  Remainder 1: 1
  Remainder 0: 3
  Remainder 2: 5
Even:
  Remainder 2: 2
  Remainder 1: 4
  Remainder 0: 6
Attempts:
2 left
💡 Hint
Group numbers by even/odd, then inside each group by remainder mod 3, watch carefully the numbers in each subgroup.

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

  1. Step 1: Understand the purpose of GroupBy

    The GroupBy method organizes elements by a key, creating groups of items sharing the same key.
  2. Step 2: Compare with other operations

    Sorting arranges order, filtering selects items, and removing duplicates eliminates repeats, which are different from grouping.
  3. Final Answer:

    It groups elements of a collection based on a key selector. -> Option B
  4. 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

  1. Step 1: Identify grouping key for first character

    Grouping by the first character means using s => s[0] as the key selector.
  2. Step 2: Check other options

    Grouping by length, uppercase string, or substring starting at index 1 does not group by first character.
  3. Final Answer:

    var groups = list.GroupBy(s => s[0]); -> Option A
  4. 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

  1. Step 1: Understand grouping key logic

    Numbers are grouped by whether they are even or odd using the key "Even" or "Odd".
  2. 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".
  3. Final Answer:

    Odd: 1,3,5 Even: 2,4,6 -> Option C
  4. 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

  1. Step 1: Check GroupBy usage

    GroupBy on List<string> with word.Length is valid syntax and logic.
  2. Step 2: Analyze output statement

    Using group.ToString() prints the type name, not the grouped items. We should join group elements to display them.
  3. Final Answer:

    Using group.ToString() instead of joining group elements. -> Option A
  4. 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

  1. Step 1: Group employees by Department

    Use GroupBy with key selector e => e.Department to group employees by their department.
  2. 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().
  3. Final Answer:

    var dict = employees.GroupBy(e => e.Department).ToDictionary(g => g.Key, g => g.Select(e => e.Name).ToList()); -> Option D
  4. 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