Agnel Kurian
Agnel Kurian

Reputation: 59466

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

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

Upvotes: 53

Views: 49568

Answers (4)

Max
Max

Reputation: 81

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)

Upvotes: 0

erikkallen
erikkallen

Reputation: 34391

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.

Upvotes: 32

Julien Roncaglia
Julien Roncaglia

Reputation: 17837

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

Upvotes: 0

Andrew Hare
Andrew Hare

Reputation: 351516

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

Upvotes: 64

Related Questions