SingleOrDefault - Safe

On the other day I ran into a task to return the only one element of a list/enumeration if exists, and I had to do it in a performant way. The list or enumeration could have any number of not null items. Using FirstOrDefault is not an option as it does not restrict having multiple items in the list. SingleOrDefault could be a choice, but it throws an exception in the case of multiple items. Handling the exception was not an option.

One solution could be to call Count and only return the first item if the value is one. The problem with this solutions is enumerating through the items to get the count for enumerable types. A better solution is to write a new SingleOrDefault extension methods to handle list and enumeration types.

Implementation

The following method is an extension of IEnumerable<T>

Find out more