C# | Union of two HashSet
A HashSet is an unordered collection of the 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 HashSet, HashSet.UnionWith(IEnumerable) Method is used.
Syntax:
firstSet.UnionWith(secondSet)
Exception: If the Set is null then this method give ArgumentNullException.
Below given are some examples to understand the implementation in a better way:
Example 1:
CSHARP
using System;
using System.Collections.Generic;
class GFG {
public static void Main()
{
HashSet< int > mySet1 = new HashSet< int >();
HashSet< int > mySet2 = new HashSet< int >();
for ( int i = 0; i < 5; i++) {
mySet1.Add(i * 2);
}
for ( int i = 0; i < 5; i++) {
mySet1.Add(i * 2 + 1);
}
HashSet< int > ans = new HashSet< int >(mySet1);
ans.UnionWith(mySet2);
foreach ( int i in ans)
{
Console.WriteLine(i);
}
}
}
|
Output:
0
2
4
6
8
1
3
5
7
9
Example 2:
CSHARP
using System;
using System.Collections.Generic;
class GFG {
public static void Main()
{
HashSet< string > mySet1 = new HashSet< string >();
HashSet< string > mySet2 = new HashSet< string >();
mySet1.Add("Hello");
mySet1.Add("GeeksforGeeks");
mySet1.Add("GeeksforGeeks");
mySet2.Add("You");
mySet2.Add("are");
mySet2.Add("the");
mySet2.Add("best");
HashSet< string > ans = new HashSet< string >(mySet1);
ans.UnionWith(mySet2);
foreach ( string i in ans)
{
Console.WriteLine(i);
}
}
}
|
Output:
Hello
GeeksforGeeks
You
are
the
best
Reference:
There are several advantages of using the Union method of HashSet<T> in C# to merge two hash sets into one. Here are some of them:
- Efficiency: The Union method is optimized for performance, and can efficiently merge two large sets into one without requiring much processing power or memory. This can be particularly useful when working with large data sets.
- No duplicates: The resulting set after the Union operation will contain only unique elements. This is because HashSet<T> does not allow duplicate entries.
- Easy to use: The Union method is very easy to use, and requires only two hash sets as input parameters. This makes it easy to use in your code without requiring any complex data processing.
- Maintainability: Using the Union method can make your code more maintainable, as it provides a clear and concise way to merge two sets together.
- Flexibility: The Union method can be used with any type of objects that can be stored in a HashSet<T>. This means that you can use it to merge sets of integers, strings, objects, or any other data type that you may be working with in your code.
Overall, the Union method of HashSet<T> provides a simple, efficient, and flexible way to merge two hash sets together in C#.
Last Updated :
12 Jun, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...