Search code examples
c#linqienumerable

LINQ Single() Exception for 0 or multiple items


I have some IEnumberable collection of items. I use .Single() to find a specific object in the collection.

I choose to use Single() because there should only ever be one specific item. However, if one doesn't exist, then I need to create it and add it to the collection.

My problem is that Single() throws the same error if there is no item matching the predicate or if there are multiple items. My idea was to put the Single() call inside of a try and catch the exception, add the item, and then continue. However, since both scenarios throw the InvalidOperationException, how can I tell if its due to no items or multiple items?

I know I can use First() but that doesn't enforce the idea that there should be only one (without doing extra work).

I could also use Count() before the Single() call, but that just seems to undermine the point of Single()


Solution

  • What you want is SingleOrDefault()

    The "or default" actually means it returns null (for reference types) or whatever the default would be for a non-reference type. You'll need to new-up an object to take its place.