How do I convert a HashSet<T> to an array in .NET?
There are two ways of converting HashSet to the array:Traverse through the HashSet and add every element to the array. To convert a HashSet into an array in java, we can use the function of toArray().
We'll leverage the same fact and to create a HashSet, we'll pass an ArrayList. Since you can use Arrays. asList() to convert an array to ArrayList, converting an array to HashSet is just a two-step job, first convert an array to a list and then convert a list to set.
In C#, HashSet is an unordered collection of unique elements. This collection is introduced in . NET 3.5. It supports the implementation of sets and uses the hash table for storage. This collection is of the generic type collection and it is defined under System.
Use the HashSet<T>.CopyTo
method. This method copies the items from the HashSet<T>
to an array.
So given a HashSet<String>
called stringSet
you would do something like this:
String[] stringArray = new String[stringSet.Count]; stringSet.CopyTo(stringArray);
If you mean System.Collections.Generic.HashSet, it's kind of hard since that class does not exist prior to framework 3.5.
If you mean you're on 3.5, just use ToArray since HashSet implements IEnumerable, e.g.
using System.Linq; ... HashSet<int> hs = ... int[] entries = hs.ToArray();
If you have your own HashSet class, it's hard to say.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With