Add elements to a HashSet in C#
This post will discuss how to add elements to a HashSet<T> in C#.
1. Using HashSet<T>.Add() Method
The HashSet<T> class is a collection that contains all unique elements, in no particular order. The HashSet<T> class provides the standard method Add which adds the specified element to it. It returns true if the element is added to the HashSet<T> and false if the element is already present.
The following example creates a HashSet<T> object and demonstrates the usage of the Add() method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Collections.Generic; public class Example { public static void Main() { HashSet<int> numbers = new HashSet<int>() { 1, 2, 3, 4 }; numbers.Add(5); Console.WriteLine(String.Join(", ", numbers)); // 1, 2, 3, 4, 5 } } |
2. Using HashSet<T>.UnionWith() Method
The HashSet<T>.UnionWith() method modifies the HashSet to contain all elements that are present in itself, the specified collection, or both. It can be used to add multiple values to an existing HashSet<T> object, as shown below:
|
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> numbers = new HashSet<int>() { 1, 2, 3, 4 }; List<int> values = new List<int>() { 4, 5 }; numbers.UnionWith(values); Console.WriteLine(String.Join(", ", numbers)); // 1, 2, 3, 4, 5 } } |
That’s all about adding elements 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 :)