Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index of value in hashset C#

Tags:

c#

Is it possible to retrieve index of value in HashSet ?

I have a hashset:

HashSet<int> allE = mesh.GetAllNGonEdges(nGonTV);

And I would like to retrieve index of value similar to arrays function: Array.IndexOf(...)

like image 511
Petras Avatar asked Jul 18 '17 09:07

Petras


1 Answers

The "index" is meaningless in a HashSet - it's not guaranteed to be the same as the insertion order, and it can change over time as you add and remove entries (in non-guaranteed ways, e.g. if you add a new entry it could end up in the middle, at the end, at the start; it could reorder everything else...) There's not even a guarantee that you'll see the same order if you iterate over the set multiple times without modifying it between times, although I'd expect that to be okay.

You can get the current index with something like:

var valueAndIndex = hashSet.Select((Value, Index) => new { Value, Index })
                           .ToList();

... but you need to be very aware that the index isn't inherent in the entry, and is basically unstable.

like image 72
Jon Skeet Avatar answered Nov 15 '22 00:11

Jon Skeet