13

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

william007
  • 15,661
  • 20
  • 90
  • 161

2 Answers2

20

You could use Single()

var element = yourHashSet.Single();
juergen d
  • 195,137
  • 36
  • 275
  • 343
  • 2
    But it is (a form of) iterating. – Henk Holterman Aug 03 '12 at 10:17
  • 5
    And requires LINQ that answer should suggest. – Feri Aug 27 '19 at 21:39
  • 1
    Ref. [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