SingleOrDefault
This C# method returns an element if a single one is present. With it you receive the single matching element, or the default value if no element is found.
Single
SingleOrDefault
has one difference to Single
. With Single
, an exception is thrown when zero matching elements are found. But with SingleOrDefault
, the default value is returned.
SingleOrDefault
exampleThis program allocates an array of 3 integers. Next, the SingleOrDefault
method is called. A Predicate
is specified to search for a single element equal to 5.
int
is returned: 0.SingleOrDefault
is called to find an element of value 1—one such element exists.SingleOrDefault
is used to find an element greater than or equal to 1. Because 3 elements match this condition, an exception is thrown.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()); } } }0 1 System.InvalidOperationException
Single
exampleThis program creates an array of 5 ints. Only one of the elements is greater than 999. Next, Single
is called with a Predicate
lambda expression.
Single
method is called on an array with only one element.Single
method, when only one match is found, returns that one element.using System; using System.Linq; class Program { static void Main() { // Find only element > 999. int[] array1 = { 1, 3, 1000, 4, 5 }; int value1 = array1.Single(element => element > 999); // Ensure only one element. int[] array2 = { 4 }; int value2 = array2.Single(); Console.WriteLine(value1); Console.WriteLine(value2); // See exception when more than one element found. try { int value3 = array1.Single(element => element > 0); } catch (Exception ex) { Console.WriteLine(ex.GetType()); } } }1000 4 System.InvalidOperationException
Single
, no matchWhat happens if no single matching element is found? Single()
tries to use a predicate that has 5 matching elements, so an exception is thrown.
Is Single
a useful method? Unfortunately, methods that can throw an exception in a normal circumstance such as Single
may be less useful.
SingleOrDefault()
method is probably useful more often. It handles the no-result case more gracefully.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.