views:

569

answers:

3

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

+6  A: 

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);
Andrew Hare
A: 

I guess

function T[] ToArray<T>(ICollection<T> collection)
{
    T[] result = new T[collection.Count];
    int i = 0;
    foreach(T val in collection)
    {
        result[i++] = val;
    }
}

as for any ICollection<T> implementation.

Actually in fact as you must reference System.Core to use the HashSet<T> class you might as well use it :

T[] myArray = System.Linq.Enumerable.ToArray(hashSet);
VirtualBlackFox
Why work hard when you have CopyTo?
Vitaliy
Because it's more generic (it applies to any ICollection<T>) and CopyTo require that you manually allocate the array anyway.
VirtualBlackFox
+2  A: 

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.

erikkallen
See the answer to this question : http://stackoverflow.com/questions/687034/using-hashset-in-c-2-0-compatible-with-3-5
VirtualBlackFox
Quote from that answer: "You can use HashSet<T> in a 2.0 application now - just reference System.Core.dll ... Note: This would require you to install the .NET 3.5 framework". IMO, if you use parts of framework 3.5, then you're using 3.5 and not 2.0. Most of the system DLLs are marked as version 2.0.0.0 even on framework 3.5.
erikkallen