william007
william007

Reputation: 18535

Get the element from hashset where hashset.Count==1

How to get the element from hashset that is known to contain exactly 1 element? (without iterating it)

Upvotes: 17

Views: 18564

Answers (3)

MHDante
MHDante

Reputation: 678

Both of the answers above are correct. It seems the only way to access the contents of HashSet<T> is through its enumerator.

That said, not all enumerators are made equal. If you are concerned with garbage allocation, It's preferable to use foreach over single. The reason being that Linq may call IEnumerable<T>.GetEnumerator() which returns an IEnumerator<T>. This boxes the enumerator.

You can avoid this by calling HashSet<T>, which returns a HashSet.Enumerator. This is a struct and does not allocate.

The answer by Randy Hall already does this (foreach doesn't use IEnumerable, it calls the method directly). But if you'd rather not stick a foreach loop in your code, you can do the iteration manually.

var set = new HashSet<String>();
set.Add("foo");

using var enumerator = set.GetEnumerator();
enumerator.MoveNext();
var result = enumerator.Current;

Console.Writeline(result); // "foo"

Keep in mind that for sets of Count != 1, this is not guaranteed to return the same element each time

Upvotes: 0

juergen d
juergen d

Reputation: 204756

You could use Single()

var element = yourHashSet.Single();

Upvotes: 24

Randy Hall
Randy Hall

Reputation: 8137

I had a HashSet<object> that for some reason couldn't be accessed with [0] or .First().

Though technically iterating, I'm leaving this here just in case someone else with my issue runs into this post.

foreach (var i in myHash){
    object o = i;
    break;
}

Simply start to iterate, then immediately break the iteration.

Upvotes: 1

Related Questions