Select an element by index from a .NET HashSet

Ventus picture Ventus · Sep 30, 2010 · Viewed 41.9k times · Source

At the moment I am using a custom class derived from HashSet. There's a point in the code when I select items under certain condition:

var c = clusters.Where(x => x.Label != null && x.Label.Equals(someLabel));

It works fine and I get those elements. But is there a way that I could receive an index of that element within the collection to use with ElementAt method, instead of whole objects?

It would look more or less like this:

var c = select element index in collection under certain condition;
int index = c.ElementAt(0); //get first index
clusters.ElementAt(index).RunObjectMthod();

Is manually iterating over the whole collection a better way? I need to add that it's in a bigger loop, so this Where clause is performed multiple times for different someLabel strings.

Edit

What I need this for? clusters is a set of clusters of some documents collection. Documents are grouped into clusters by topics similarity. So one of the last step of the algorithm is to discover label for each cluster. But algorithm is not perfect and sometimes it makes two or more clusters with the same label. What I want to do is simply merge those cluster into big one.

Answer

Jon Skeet picture Jon Skeet · Sep 30, 2010

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.