Bird
0
0

Given a List<int> named numbers containing {1, 2, 3, 4, 5}, which code snippet correctly doubles each number in the list?

hard🚀 Application Q15 of 15
C Sharp (C#) - Collections
Given a List<int> named numbers containing {1, 2, 3, 4, 5}, which code snippet correctly doubles each number in the list?
Anumbers = numbers.Select(n => n * 2).ToList();
Bfor (int i = 0; i < numbers.Count; i++) { numbers[i] = numbers[i] * 2; }
Cforeach (int n in numbers) { n = n * 2; }
Dnumbers.ForEach(n => n = n * 2);
Step-by-Step Solution
Solution:
  1. Step 1: Understand how to modify List elements

    Using a for loop with index allows modifying elements directly by assignment.
  2. Step 2: Evaluate each option's effect

    for (int i = 0; i < numbers.Count; i++) { numbers[i] = numbers[i] * 2; } modifies elements in place. foreach (int n in numbers) { n = n * 2; } modifies copy of elements (no effect). numbers = numbers.Select(n => n * 2).ToList(); creates a new list but requires LINQ and ToList(). numbers.ForEach(n => n = n * 2); modifies copies in ForEach (no effect).
  3. Final Answer:

    for (int i = 0; i < numbers.Count; i++) { numbers[i] = numbers[i] * 2; } -> Option B
  4. Quick Check:

    Use for loop with index to update List elements [OK]
Quick Trick: Use for loop with index to update List items directly [OK]
Common Mistakes:
MISTAKES
  • Using foreach expecting to modify list items
  • Using ForEach with lambda that doesn't assign back
  • Not creating new list when using LINQ Select

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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