Bird
0
0

You have a list of integers with duplicates: List<int> nums = new List<int> {1, 2, 2, 3, 4, 4, 4, 5};

hard🚀 Application Q15 of 15
C Sharp (C#) - Collections
You have a list of integers with duplicates: List<int> nums = new List<int> {1, 2, 2, 3, 4, 4, 4, 5};
Which code snippet correctly creates a HashSet<int> containing only the unique elements from nums?
Avar unique = new HashSet<int>(nums);
Bvar unique = new HashSet<int>(); unique.Add(nums);
Cvar unique = new HashSet<int>(); foreach(var n in nums) unique = n;
Dvar unique = new HashSet<int>(); unique.AddRange(nums);
Step-by-Step Solution
Solution:
  1. Step 1: Understand HashSet constructor

    HashSet has a constructor that accepts an IEnumerable<T> to initialize with unique elements.
  2. Step 2: Analyze each option

    var unique = new HashSet(nums); correctly passes the list to the constructor. var unique = new HashSet(); unique.Add(nums); tries to add the whole list as one item (invalid). var unique = new HashSet(); foreach(var n in nums) unique = n; assigns int to HashSet variable (invalid). var unique = new HashSet(); unique.AddRange(nums); uses AddRange which HashSet does not have.
  3. Final Answer:

    var unique = new HashSet(nums); -> Option A
  4. Quick Check:

    Use constructor with collection for unique set [OK]
Quick Trick: Pass list to HashSet constructor for unique items [OK]
Common Mistakes:
MISTAKES
  • Using Add to add whole list at once
  • Trying to assign int to HashSet variable
  • Using AddRange which HashSet lacks

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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