Merge two HashSets in C#
This post will discuss how to merge two HashSets in C#.
1. Using HashSet<T>.UnionWith() Method
The shortest and most idiomatic way to merge contents of a HashSet<T> object with contents of another HashSet<T> is using the HashSet<T>.UnionWith() method. It modifies the HashSet<T> to contain all elements that are present in itself along with elements in the specified HashSet (or any other IEnumerable in general). It can be used to add multiple values to an existing HashSet<T> object, as shown below:
For example, the following code merges all the elements contained in the second set with the elements contained in the first set. Note that a set permits no duplicate elements.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Collections.Generic; public class Example { public static void Main() { HashSet<int> set1 = new HashSet<int>() { 2, 3, 4 }; HashSet<int> set2 = new HashSet<int>() { 4, 5, 6 }; set1.UnionWith(set2); Console.WriteLine(String.Join(", ", set1)); // 2, 3, 4, 5, 6 } } |
2. Using foreach loop
Alternatively, you can iterate over the second set using a foreach loop and add each element to the first set. The following code example demonstrates this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Collections.Generic; public class Example { public static void Main() { HashSet<int> set1 = new HashSet<int>() { 2, 3, 4 }; HashSet<int> set2 = new HashSet<int>() { 4, 5, 6 }; foreach (var item in set2) { set1.Add(item); } Console.WriteLine(String.Join(", ", set1)); // 2, 3, 4, 5, 6 } } |
That’s all about merging two HashSets in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)