user222427
user222427

Reputation:

Get element of HashSet<T> by position

Is there a way to grab the third row from a HashSet? Like

HashSet<string> ContinuedForums = new HashSet<string>();
ContinuedForums.add("a");
ContinuedForums.add("b");
string hellow = ContinuedForums[1];

Yes I want to use a HashSet.

Upvotes: 6

Views: 12055

Answers (4)

cat_in_hat
cat_in_hat

Reputation: 705

If the order in the set is important you may use SortedSet.

This won't give you items in the order in which you added them, it will sort them instead.

Upvotes: 1

If you are talking about "third" in the context of third one added, then there is no way. That information is not exposed by HashSet. It is an undocumented side effect of the internal implementation of HashSet that if you add these strings to a HashSet: "one", "two", "three", you will get the contents back in the same order they were added if you enumerate over its contents. But since this is undocumented behavior, it would be a big mistake to write code that depends on that behavior. The reason is that future versions of HashSet may behave in an entirely different way. Also note that if you were to remove "two" from the HashSet, and then add "four", enumerating over the HashSet will likely then return "one", "four", "three".

The whole notion of "Position" is an internal implementation detail of HashSet. It exposes nothing in its methods and properties that makes any promise of providing information about position. So, as far as users of HashSet are concerned, the concept of position does not exist.

Upvotes: 1

Haney
Haney

Reputation: 34922

If you want to balance the order with performance, you're likely better off keeping two structures... The HashSet<T> for O(1) lookups and a List<T> for enumeration (or quick index accessor lookup).

Upvotes: 4

Reed Copsey
Reed Copsey

Reputation: 564911

A HashSet<T> is by its nature unordered.

You can grab the third element via ContinuedForums.Skip(2).First(), but this won't necessarily be the "third" element you added, and the ordering will change as you add or remove elements.

If you need to preserve the order, then a HashSet<T> is likely the wrong collection type to use. It is not intended to preserve order or access by index.

Upvotes: 16

Related Questions