Bird
Raised Fist0

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🚀 Application Q15 of Q15
C Sharp (C#) - LINQ Fundamentals
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?
Avar dict = employees.GroupBy(e => e.Name).ToDictionary(g => g.Key, g => g.Select(e => e.Department).ToList());
Bvar dict = employees.ToDictionary(e => e.Department, e => e.Name);
Cvar dict = employees.GroupBy(e => e.Department).ToList();
Dvar dict = employees.GroupBy(e => e.Department).ToDictionary(g => g.Key, g => g.Select(e => e.Name).ToList());
Step-by-Step Solution
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]
Quick Trick: GroupBy then ToDictionary with Select for values list [OK]
Common Mistakes:
MISTAKES
  • Using ToDictionary directly without grouping
  • Grouping by Name instead of Department
  • Not converting grouped items to list of names

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes