简体   繁体   English

简洁的方法来获取HashSet中包含的单个元素,C#

[英]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. 我可以肯定地知道,在我程序的特定点上,我构建的HashSet将仅包含一个元素。 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. 但是,当我确定HashSet仅包含单个项目时,我不喜欢使用for循环的想法。 I know HashSet s are unordered and understand why using, say, an array-style index won't work. 我知道HashSet是无序的,并且理解为什么不能使用例如数组样式的索引。 Are there any solutions that will make it clear that only a single element exists in the HashSet ? 是否有任何解决方案可以明确表明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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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