Bird
0
0

Given a list of user IDs and names:

hard🚀 Application Q15 of 15
C Sharp (C#) - Collections
Given a list of user IDs and names:
var users = new List<(int id, string name)> { (1, "Alice"), (2, "Bob"), (3, "Charlie") };

Which code correctly creates a Dictionary<int, string> mapping IDs to names using a dictionary comprehension style?
Avar dict = users.ToDictionary(u => u.id, u => u.name);
Bvar dict = new Dictionary<int, string>(); foreach(var u in users) dict.Add(u.name, u.id);
Cvar dict = users.Select(u => new { u.id, u.name }).ToList();
Dvar dict = new Dictionary<string, int>(); foreach(var u in users) dict[u.id] = u.name;
Step-by-Step Solution
Solution:
  1. Step 1: Understand ToDictionary usage

    ToDictionary converts a list to a dictionary by specifying key and value selectors.
  2. Step 2: Check each option

    var dict = users.ToDictionary(u => u.id, u => u.name); correctly maps id to name. var dict = new Dictionary<int, string>(); foreach(var u in users) dict.Add(u.name, u.id); swaps key and value and uses wrong types. var dict = users.Select(u => new { u.id, u.name }).ToList(); creates a list, not dictionary. var dict = new Dictionary<string, int>(); foreach(var u in users) dict[u.id] = u.name; has wrong dictionary types and indexer usage.
  3. Final Answer:

    var dict = users.ToDictionary(u => u.id, u => u.name); -> Option A
  4. Quick Check:

    ToDictionary creates dictionary from list [OK]
Quick Trick: Use ToDictionary with key and value selectors [OK]
Common Mistakes:
MISTAKES
  • Swapping key and value in Add
  • Using Select instead of ToDictionary
  • Mismatching dictionary key-value types

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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