How do I convert a HashSet<T> to an array in .NET?
Asked
Active
Viewed 4.5k times
50
-
5`HashSet
` is only available in **.Net 3.5**. As such, you can use the `ToArray()` Linq extension method. – adrianbanks Oct 21 '09 at 21:23 -
1@adrianbanks: Thanks. Anyway, I edited the question to match the answers better. – Agnel Kurian Oct 21 '09 at 21:31
4 Answers
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
-
2
-
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 – Feb 12 '13 at 11:42implements ICollection and LINQ's .ToArray() implementation has a special case for ICollection 's).
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
-
1Quote 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
-
1Because it's more generic (it applies to any ICollection
) and CopyTo require that you manually allocate the array anyway. – Julien Roncaglia Oct 21 '09 at 21:16
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