Bird
0
0

Given two HashSet<string> objects setA and setB, how do you create a new HashSet containing only elements present in both sets?

hard🚀 Application Q9 of 15
C Sharp (C#) - Collections
Given two HashSet<string> objects setA and setB, how do you create a new HashSet containing only elements present in both sets?
Avar intersection = setA.Union(setB);
Bvar intersection = setA + setB;
Cvar intersection = new HashSet<string>(setA); intersection.IntersectWith(setB);
Dvar intersection = setA.Except(setB);
Step-by-Step Solution
Solution:
  1. Step 1: Use IntersectWith to find common elements

    Creating a new HashSet from setA and calling IntersectWith(setB) keeps only common elements.
  2. Step 2: Check other options

    var intersection = setA + setB; is invalid syntax, C returns union, D returns elements in setA not in setB.
  3. Final Answer:

    var intersection = new HashSet<string>(setA); intersection.IntersectWith(setB); -> Option C
  4. Quick Check:

    HashSet intersection = IntersectWith() method [OK]
Quick Trick: Use IntersectWith() to keep common elements in HashSet [OK]
Common Mistakes:
MISTAKES
  • Using + operator for sets
  • Confusing Union with Intersection
  • Using Except instead of IntersectWith

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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