Initialize a HashSet in C#
This post will discuss how to initialize a HashSet<T> in C#.
We can use object initializers to initialize a HashSet<T> in C#, introduced in C# 3.0. It consists of a sequence of elements, enclosed within { and } where each member is separated by a comma. This causes each of the specified elements to be added to the HashSet<T> object, without explicitly invoking the constructor.
The following example shows how to initialize a new HashSet<int> by using object initializers.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
using System; using System.Collections.Generic; public class Example { public static void Main() { HashSet<int> numbers = new HashSet<int>() { 1, 2, 3 }; Console.WriteLine(String.Join(", ", numbers)); // 1, 2, 3 } } |
Alternatively, you can invoke the HashSet<T> constructor to initialize a new instance of the HashSet<T> class with elements of the specified collection. For example, the following code initializes a HashSet<T> with distinct elements of a List<T>, in no particular order.
|
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() { List<int> collection = new List<int>() { 1, 3, 2, 1 }; HashSet<int> numbers = new HashSet<int>(collection); Console.WriteLine(String.Join(", ", numbers)); // 1, 3, 2 } } |
If you need to add the specified element to an existing HashSet<int> object, consider using the standard Add method. The following code example demonstrates this:
|
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>(); numbers.Add(1); numbers.Add(2); numbers.Add(3); Console.WriteLine(String.Join(", ", numbers)); // 1, 2, 3 } } |
That’s all about initializing 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 :)