LINQ: Single vs. SingleOrDefault
Posted
by Paulo Morgado
on ASP.net Weblogs
See other posts from ASP.net Weblogs
or by Paulo Morgado
Published on Tue, 30 Mar 2010 00:40:36 GMT
Indexed on
2010/03/30
0:43 UTC
Read the original article
Hit count: 470
Like all other LINQ API methods that extract a scalar value from a sequence, Single has a companion SingleOrDefault.
The documentation of SingleOrDefault states that it returns a single, specific element of a sequence of values, or a default value if no such element is found, although, in my opinion, it should state that it returns a single, specific element of a sequence of values, or a default value if no such element is found. Nevertheless, what this method does is return the default value of the source type if the sequence is empty or, like Single, throws an exception if the sequence has more than one element.
I received several comments to my last post saying that SingleOrDefault could be used to avoid an exception.
Well, it only “solves” half of the “problem”. If the sequence has more than one element, an exception will be thrown anyway.
In the end, it all comes down to semantics and intent. If it is expected that the sequence may have none or one element, than SingleOrDefault should be used. If it’s not expect that the sequence is empty and the sequence is empty, than it’s an exceptional situation and an exception should be thrown right there. And, in that case, why not use Single instead? In my opinion, when a failure occurs, it’s best to fail fast and early than slow and late.
Other methods in the LINQ API that use the same companion pattern are: ElementAt/ElementAtOrDefault, First/FirstOrDefault and Last/LastOrDefault.
© ASP.net Weblogs or respective owner