Mid Collections

How do you perform a union or intersection between two HashSet<T> objects?

Union: Combines all unique elements from both sets

set1.UnionWith(set2);

Intersection: Keeps only elements present in both sets

set1.IntersectWith(set2);

Example:

HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };

HashSet<int> set2 = new HashSet<int> { 3, 4, 5 };

set1.UnionWith(set2); // set1 = {1, 2, 3, 4, 5}

Follow:

set1.IntersectWith(set2); // set1 = {3, 4, 5}

More from C# Programming Tutorial

All questions for this course