Bird
Raised Fist0

Given a list of products with properties Name and Category, how would you use GroupBy in C# to create a dictionary where keys are categories and values are lists of product names?

hard🚀 Application Q8 of Q15
C Sharp (C#) - LINQ Fundamentals
Given a list of products with properties Name and Category, how would you use GroupBy in C# to create a dictionary where keys are categories and values are lists of product names?
Avar dict = products.GroupBy(p => p.Category).ToDictionary(g => g.Key, g => g.Select(p => p.Name).ToList());
Bvar dict = products.ToDictionary(p => p.Category, p => p.Name);
Cvar dict = products.GroupBy(p => p.Name).ToDictionary(g => g.Key, g => g.Select(p => p.Category).ToList());
Dvar dict = products.GroupBy(p => p.Category).ToList();
Step-by-Step Solution
Solution:
  1. Step 1: Group products by Category

    Use GroupBy(p => p.Category) to group products by their category.
  2. Step 2: Convert groups to dictionary

    Use ToDictionary with key as group.Key (category) and value as list of product names in that group.
  3. Step 3: Select product names

    Use g.Select(p => p.Name).ToList() to get list of product names per category.
  4. Final Answer:

    var dict = products.GroupBy(p => p.Category).ToDictionary(g => g.Key, g => g.Select(p => p.Name).ToList()); -> Option A
  5. Quick Check:

    GroupBy then ToDictionary with key and projected values [OK]
Quick Trick: Group then project values before ToDictionary [OK]
Common Mistakes:
MISTAKES
  • Using ToDictionary directly without grouping
  • Grouping by wrong property
  • Not projecting group elements to desired value

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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