C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
On empty collections, it returns the default value for the type. With it you receive the single matching element, or the default value if no element is found.
Example. This program allocates an array of three integers. Next, the SingleOrDefault method is called. A Predicate is specified to search for a single element equal to 5. No such element exists, so the default value of int is returned: 0.
Next, SingleOrDefault is called to find an element of value 1—one such element exists. Finally, SingleOrDefault is used to find an element >= 1. Because three elements match this condition, an exception is thrown.
Lambda ExpressionInvalidOperationException
C# program that uses SingleOrDefault method using System; using System.Linq; class Program { static void Main() { int[] array = { 1, 2, 3 }; // Default is returned if no element found. int a = array.SingleOrDefault(element => element == 5); Console.WriteLine(a); // Value is returned if one is found. int b = array.SingleOrDefault(element => element == 1); Console.WriteLine(b); try { // Exception is thrown if more than one is found. int c = array.SingleOrDefault(element => element >= 1); } catch (Exception ex) { Console.WriteLine(ex.GetType()); } } } Output 0 1 System.InvalidOperationException
Single. What is the difference between Single and SingleOrDefault? The difference is what happens when zero matching elements are found. With Single, an exception is thrown in this case. But with SingleOrDefault, the default value is returned.
Note: For ints, the default value is 0. You can find default values with the default operator.
Summary. SingleOrDefault helps ensure zero or one elements exist matching a condition. As with Single, it can be used with no parameters to match all elements. Its behavior on multiple matches, which results in an exception, can be confusing.