Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a HashSet<T> to an array in .NET

How do I convert a HashSet<T> to an array in .NET?

like image 486
Agnel Kurian Avatar asked Oct 21 '09 21:10

Agnel Kurian


People also ask

How do I convert a HashSet to an array?

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().

Can you make a HashSet of arrays?

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.

What is hash set in C#?

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.


2 Answers

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); 
like image 192
Andrew Hare Avatar answered Sep 19 '22 16:09

Andrew Hare


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.

like image 23
erikkallen Avatar answered Sep 23 '22 16:09

erikkallen