Reputation: 10016
I know for sure that at a particular point in my program a HashSet
I've constructed will only contain a single element. I know I can get the element by doing this:
foreach (int num in myHashSet)
{
return num;
}
But I don't like the idea of using a for loop when I'm certain that the HashSet
only contains a single item. I know HashSet
s are unordered and understand why using, say, an array-style index won't work. Are there any solutions that will make it clear that only a single element exists in the HashSet
? I feel that with a loop this property isn't clear.
Upvotes: 0
Views: 830
Reputation: 7344
HashSet<int> ihs = new HashSet<int>();
ihs.Add(12);
if (ihs.Count() == 1)
{
int x = ihs.First();
}
Upvotes: 4