Add elements of a List to a HashSet in C#
This post will discuss how to add elements of a List<T> to a HashSet<T> in C#.
1. Using HashSet<T>.UnionWith() Method
The HashSet<T>.UnionWith() method modifies the HashSet by merging all its elements with the specified collection. The following example demonstrates the usage of the UnionWith() method by adding elements of a List<T> to an existing HashSet<T>:
|
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() { List<int> list = new List<int>() { 2, 3, 4 }; HashSet<int> set = new HashSet<int>() { 1, 2, 4, 7 }; set.UnionWith(list); Console.WriteLine(String.Join(", ", set)); // 1, 2, 4, 7, 3 } } |
2. Using foreach loop
Alternatively, you can create an extension method that act as AddRange() equivalent for a HashSet<T>. It adds elements of the specified collection to a HashSet<T> using a foreach loop. Note that a Set data structure doesn’t permit duplicates and maintains no particular order of its elements.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
using System; using System.Collections.Generic; public static class Extensions { public static void AddRange<T>(this HashSet<T> source, IEnumerable<T> collection) { foreach (T item in collection) { source.Add(item); } } } public class Example { public static void Main() { List<int> list = new List<int>() { 2, 3, 4 }; HashSet<int> set = new HashSet<int>() { 1, 2, 4, 7 }; set.AddRange(list); Console.WriteLine(String.Join(", ", set)); // 1, 2, 4, 7, 3 } } |
3. Using Enumerable.Concat() Method
Both above solutions add all elements of the List<T> to the HashSet<T>. You can use LINQ’s Enumerable.Concat() method to create a new collection containing elements of both the source set and the given list.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<int> list = new List<int>() { 2, 3, 4 }; HashSet<int> set = new HashSet<int>() { 1, 2, 4, 7 }; HashSet<int> union = set.Concat(list).ToHashSet(); Console.WriteLine(String.Join(", ", union)); // 1, 2, 4, 7, 3 } } |
That’s all about adding elements of a List<T> to a HashSet<T> 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 :)