c00000fd
c00000fd

Reputation: 22327

Efficient way to get all elements from a HashSet in .NET

Say, I have a HashSet with elements:

HashSet<int> hsData = new HashSet<int>();

and at some point I need to process those elements (one by one). I can of course convert it into an array and work with it that way:

int[] arr = hsData.ToArray();

but I'm not sure how efficient this conversion will be?

I see that people recommend using foreach on the HashSet itself, but due to architecture of my code, I cannot use it. I need something that can work as such:

Is it the last element? If no, then get it and advance to next element.

Upvotes: 0

Views: 8184

Answers (3)

cskwg
cskwg

Reputation: 849

ToArray does not (yet) exist, but you can use CopyTo

Upvotes: 0

Elad Lachmi
Elad Lachmi

Reputation: 10581

As you stated, converting to an array can have some performance drawbacks. What foreach does behind the scenes is get an enumerator in the HashSet and run through it.

HashSet<T> also implements IEnumerable<T>, which can be used to enumerate the collection in a much more efficient way. Look here for a reference on IEnumerable.

Upvotes: 3

Vaughan Hilts
Vaughan Hilts

Reputation: 2879

You can use a foreach still if you'd like. Just keep a running counter of all the elements in the given list, decrement as you do an iteration, and do a comparison against the counter.

On the other hand, is turning it into an array a big deal? Is this operation happening 1000s of times?

Upvotes: 0

Related Questions