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

Agnel Kurian picture Agnel Kurian · Oct 21, 2009 · Viewed 32.1k times · Source

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

Answer

Andrew Hare picture Andrew Hare · Oct 21, 2009

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);