Select an element by index from a .NET HashSet

There's no such thing as an index with a hash set. One of the ways that hash sets gain efficincy in some cases is by not having to maintain them.

I also don't see what the advantage is here. If you were to obtain the index, and then use it this would be less efficient than just obtaining the element (obtaining the index would be equally efficient, and then you've an extra operation).

If you want to do several operations on the same object, just hold onto that object.

If you want to do something on several objects, do so on the basis of iterating through them (normal foreach or doing foreach on the results of a Where() etc.). If you want to do something on several objects, and then do something else on those several same objects, and you have to do it in such batches, rather than doing all the operations in the same foreach then store the results of the Where() in a List<T>.


Sets don't generally have indexes. If position is important to you, you should be using a List<T> instead of (or possibly as well as) a set.

Now SortedSet<T> in .NET 4 is slightly different, in that it maintains a sorted value order. However, it still doesn't implement IList<T>, so access by index with ElementAt is going to be slow.

If you could give more details about why you want this functionality, it would help. Your use case isn't really clear at the moment.


In the case where you hold elements in HashSet and sometimes you need to get elements by index, consider using extension method ToList() in such situations. So you use features of HashSet and then you take advantage of indexes.

HashSet<T> hashset = new HashSet<T>();

//the special situation where we need index way of getting elements
List<T> list = hashset.ToList();

//doing our special job, for example mapping the elements to EF entities collection (that was my case)

//we can still operate on hashset for example when we still want to keep uniqueness through the elements 

Tags:

C#

.Net

Hashset