Click here to Skip to main content
15,878,945 members
Articles / Programming Languages / C# 4.0

LINQ: Single vs. SingleOrDefault

Rate me:
Please Sign up or sign in to vote.
4.50/5 (2 votes)
15 Apr 2010CPOL1 min read 24.3K   4  
LINQ: Single vs SingleOrDefault

free hit countersLike 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 THE single, specific element of a sequence of ONE value, 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, then SingleOrDefault should be used. If it’s not, expect that the sequence is empty and the sequence is empty, then 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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Paulo Morgado
Portugal Portugal

Comments and Discussions

 
-- There are no messages in this forum --