![]() |
VOOZH | about |
A HashSet is an unordered collection of unique elements. It comes under the System.Collections.Generic namespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list. For the Union of two HashSets, we can use the method HashSet<T>.UnionWith(IEnumerable<T> other) method to perform the union operation.
Syntax:
void HashSet<T>.UnionWith(IEnumerable<T> other)
Example 1: Performing Union operation using the method HashSet<int>.UnionWith(IEnumerable<int> other)
HashSet s1: 0 2 4 6 8 HashSet s2: 1 3 5 7 9 Union of s1 and s2: 0, 2, 4, 6, 8, 1, 3, 5, 7, 9 HashSet s3: 0 3 5 7 9 10 HashSet s4: 1 3 5 7 9 Union of s3 and s4: 0, 3, 5, 7, 9, 10, 1
Example 2: Performing Union Operations on HashSets of strings.
Elements of HashSet s1: Hello GeeksforGeeks Elements of HashSet s2: You are the best Elements of the Union set: Hello GeeksforGeeks You are the best