Bird
0
0

You want to initialize a dictionary where keys are strings and values are lists of integers. Which is the correct way to do this in C#?

hard🚀 Application Q15 of 15
C Sharp (C#) - Collections
You want to initialize a dictionary where keys are strings and values are lists of integers. Which is the correct way to do this in C#?
Avar dict = new Dictionary<string, List<int>> { { "a", new List<int> {1, 2} }, { "b", new List<int> {3, 4} } };
Bvar dict = new Dictionary<string, List<int>> { { "a", {1, 2} }, { "b", {3, 4} } };
Cvar dict = new Dictionary<string, List<int>> { ( "a", [1, 2] ), ( "b", [3, 4] ) };
Dvar dict = new Dictionary<string, List<int>> { "a": [1, 2], "b": [3, 4] };
Step-by-Step Solution
Solution:
  1. Step 1: Understand nested collection initialization

    Each dictionary value is a List, so you must create new List instances inside the dictionary initializer.
  2. Step 2: Check syntax correctness

    var dict = new Dictionary> { { "a", new List {1, 2} }, { "b", new List {3, 4} } }; correctly uses nested initializers: dictionary with key-value pairs, where values are new List with their own initializers.
  3. Final Answer:

    var dict = new Dictionary> { { "a", new List {1, 2} }, { "b", new List {3, 4} } }; -> Option A
  4. Quick Check:

    Nested collections need explicit new List [OK]
Quick Trick: Use 'new' for nested collections inside dictionary [OK]
Common Mistakes:
MISTAKES
  • Omitting 'new List' for nested lists
  • Using parentheses or brackets incorrectly
  • Trying to use colon syntax inside C# initializers

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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