Click here to Skip to main content
Click here to Skip to main content
Technical Blog

LINQ: Single vs. SingleOrDefault

, 15 Apr 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
Like 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
LINQ With C# (Portuguese)

Like other LINQ API methods that extract a scalar value from a sequence, Single has a companion SingleOrDefault.

free hit counters

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.

free hit counters

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.

License

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

Share

About the Author

Paulo Morgado
Software Developer (Senior) Paulo Morgado
Portugal Portugal

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.141216.1 | Last Updated 15 Apr 2010
Article Copyright 2010 by Paulo Morgado
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid