tags:

views:

43

answers:

2
+1  A: 

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.

Jon Skeet
I have added more detailed description of a problem as you asked :)
Ventus
@Ventus: That doesn't really explain why you need the index. If you just want to run a method for each matching item, a simple foreach loop is definitely the way forward... did you have a particular reason for wanting an index?
Jon Skeet
Obviously my language skills (I mean English) is not perfect, although I wanted to modify 2 elements in collection at the same time. Yet, your suggestion to use `List` instead of set was good idea, so problem is solved and your answer is accepted.
Ventus
A: 

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>.

Jon Hanna