The InvalidOperationException: Sequence contains no elements exception is thrown whenever you try to retreive an element from an empty sequence. This generally happens when you call First on an empty sequence. What I think about for this situation is that I'ld need a method which would return null if the sequence is empty and the first object (maybe the only object) in the sequence otherwise.
In this case the call of FirstOrDefault is recomended. Although after a few searches I've found something similar: we could Single or SingleOrDefault instead of First. Calling these methods is almost exactly what First does except ... this will generate another exception if the sequest contains more elements: InvalidOperationException: Sequence contains more than one element. But the convenient factor is that it quietly returns the single element in a sequence, null of the sequence is empty and the above mentioned InvalidOperationException: Sequence contains more than one element.
» Continue reading ...