Create copy of a HashSet in C#
This post will discuss how to create a copy of a HashSet<T> in C#.
The HashSet<T> class provides a Constructor that takes a collection and initializes a new instance of the HashSet<T> class with the elements copied from the specified collection. The following example demonstrate creating a new HashSet<T> instance from an existing Set.
|
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, 5 }; HashSet<int> clone = new HashSet<int>(numbers); Console.WriteLine(String.Join(", ", clone)); // 1, 2, 3, 4, 5 } } |
You can also create a ToHashSet extension method to create a copy of a HashSet<T> is using its constructor, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; using System.Collections.Generic; public static class Extensions { public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source) { return new HashSet<T>(source); } } public class Example { public static void Main() { HashSet<int> numbers = new HashSet<int>() { 1, 2, 3, 4, 5 }; HashSet<int> clone = numbers.ToHashSet(); Console.WriteLine(String.Join(", ", clone)); // 1, 2, 3, 4, 5 } } |
The HashSet<T> class provides has another overload that ensures the same equality comparer is used as the original Set. For example, the following code uses a supplied comparer to allow case-insensitive comparisons on the elements of a HashSet<T> collection.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
using System; using System.Collections.Generic; public static class Extensions { public static HashSet<T> ToHashSet<T>(this HashSet<T> source) { return new HashSet<T>(source, source.Comparer); } } public class Example { public static void Main() { HashSet<string> numbers = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "A", "a", "B", "C" }; HashSet<string> clone = numbers.ToHashSet(); Console.WriteLine(String.Join(", ", clone)); // A, B, C } } |
That’s all about creating a copy of 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 :)