Geeks With Blogs
Abhishek Anand Bits & Bytes about .net technology framework.

The goal of both the Single and SingleOrDefault methods is the same: get one element in the collection that matches the provided predicate. The difference between the two lies in their behavior when no matching element is found. The Single method will throw an error saying something like “Sequence contains no elements”, while the SingleOrDefault() method will return the default value of the collection’s type. For reference types and nullable, it will return null and for value types it will return an actual value such as zero for numeric. Similar to the .Any() method, both have an overload for not providing a predicate. In this case, the method will attempt to return a single element from the collection. If none exists, the same behavior as discussed above will occur. 

When more than one matching element is found, however, both methods throw an exception such as “Sequence contains more than one element”.

            var arr = new[] { 1, 2, 3, 4, 5, 6 };

            var elem = arr.Single(); //Throws Exception (more than 1)

            var elem2 = arr.SingleOrDefault(); //Throws Exception (more than 1)

            var elem3 = arr.Single(item => item > 10); //Throws Exception (none matching)

            var elem4 = arr.SingleOrDefault(item => item > 10); //Returns 0 (none matching)

Posted on Monday, November 18, 2013 6:17 PM .net , linq , c# | Back to top


Comments on this post: .Single() vs. .SingleOrDefault()

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Abhishek Anand | Powered by: GeeksWithBlogs.net