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.
This is all fine until you are into ADO.NET Entity Framework like me recently. Because you are used to working by using .Single() and .SingleOrDefault() you think it's the same procedure while querying an entity data model. And you won't be pleased to see the following exception: NotSupportedException: The method 'Single' is not supported by LINQ to Entities. Consider using the method 'First' instead.
A solution to the unsuported call of Single on LINQ to Entities is the following. The query can be transformed to LINQ to Objects by calling ToList or ToArray, and because LINQ to Objects supports the Single Method, we can now call Single on the returned IEnumerable<TSource> type (Ex: .ToList().Single()). Like this we can still enjoy the ADO.NET Entity Framework and also use the Single method.
Any other ideas or solutions are welcome!