We have many ways in C# to merge the HashSet<T>
easily. We will merge HashSet<T>
using the below options in C#,
HashSet<T>.UnionWith()
Methodforeach
loop
Using HashSet<T>.UnionWith()
Method
The easiest way to merge one HashSet<T>
with another HashSet<T>
is by using HashSet<T>.UnionWith() in C#. We can as many elements or values in the hash set in C# and we can merge them using UnionWidth()
using System;
using System.Collections.Generic;
namespace MergeHashSets
{
class Program
{
public static void Main()
{
// HashSet 1
HashSet<int> hashSet1 = new HashSet<int>() { 1, 2, 3, 4 };
// HashSet 2
HashSet<int> hashSet2 = new HashSet<int>() { 3, 5, 6, 7, 1 };
hashSet1.UnionWith(hashSet2);
Console.WriteLine(String.Join(", ", hashSet1));
Console.ReadKey();
}
}
}
Output:
1, 2, 3, 4, 5, 6, 7
Using foreach
loop
We can also use the foreach
loop to merge two HashSet<T>
in C# as shown below,
using System;
using System.Collections.Generic;
namespace MergeHashSets
{
class Program
{
public static void Main()
{
// HashSet 1
HashSet<int> hashSet1 = new HashSet<int>() { 1, 2, 3, 4 };
// HashSet 2
HashSet<int> hashSet2 = new HashSet<int>() { 3, 5, 6, 7, 1 };
foreach (var hashset in hashSet2)
{
hashSet1.Add(hashset);
}
Console.WriteLine(String.Join(", ", hashSet1));
Console.ReadKey();
}
}
}
Output:
1, 2, 3, 4, 5, 6, 7
Comments (0)