How to get the element from hashset that is known to contain exactly 1 element? (without iterating it)
Asked
Active
Viewed 1.2k times
2 Answers
20
-
2But it is (a form of) iterating. – Henk Holterman Aug 03 '12 at 10:17
-
5And requires LINQ that answer should suggest. – Feri Aug 27 '19 at 21:39
-
1Ref. [this answer](https://stackoverflow.com/questions/2724096/linq-single-vs-first#answer-2724246) to whether `.First()` or `.Single()` should be used, I'd suggest using `.Single()` rather than `.First()` -- seeing as getting the knowingly only item in the hash set is the intent here. – Astrid E. Feb 08 '22 at 07:32
-1
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.
Randy Hall
- 7,002
- 14
- 69
- 130