50

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

Agnel Kurian
  • 57,975
  • 43
  • 146
  • 217

4 Answers4

63

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
  • 344,730
  • 71
  • 640
  • 635
  • 15
    HashSet.ToArray() is simpler – Michael Freidgeim Dec 09 '11 at 02:21
  • 2
    Is there an ToArray? I can't seem to find it – Konstantin Dec 19 '12 at 09:38
  • 12
    @Konstantin HashSet has a .ToArray() method but it is internal. However, you can use LINQ's .ToArray() extension method which internally uses .CopyTo() (because HashSet implements ICollection and LINQ's .ToArray() implementation has a special case for ICollection's). –  Feb 12 '13 at 11:42
31

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
  • 33,800
  • 13
  • 85
  • 120
  • See the answer to this question : http://stackoverflow.com/questions/687034/using-hashset-in-c-2-0-compatible-with-3-5 – Julien Roncaglia Oct 21 '09 at 21:24
  • 1
    Quote from that answer: "You can use HashSet 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 Oct 22 '09 at 10:30
0

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);
Julien Roncaglia
  • 17,397
  • 4
  • 57
  • 75
0

Now you can do it even simpler, with List<T> constructor (Lists are modern Arrays :). E. g., in PowerShell:

$MyNewArray = [System.Collections.Generic.List[string]]::new($MySet)
Max
  • 71
  • 3
  • 8