简体   繁体   中英

Concise way to get the single element contained in a HashSet, C#

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.

HashSet<int> ihs = new HashSet<int>();
ihs.Add(12);
if (ihs.Count() == 1)
{
    int x = ihs.First();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM