SingleOrDefault<TSource>(IEnumerable<TSource>) Method

public static TSource SingleOrDefault<TSource>(this IEnumerable<TSource> source)
Returns the single element of a sequence, or a default value if the sequence is empty; by reference to the single element of a sequence that must contain exactly one element.

This method is the equivalent of SingleOrDefault(IEnumerable<TSource>, Int32) when the predicate is always true.
Namespace: System.Linq
Assembly: System.Linq.dll

Parameters

Returns

TSource

The single element of the input sequence, or default(TSource) if the sequence is empty.

Exceptions

Remarks

If the sequence is empty, this method returns the default value for the element type.

If the sequence contains more than one element, this method throws an InvalidOperationException.

This method performs a deferred execution.

Examples

Example 1: Basic usage with a single element

using System; using System.Collections.Generic; using System.Linq; public class Example { public static void Main(string[] args) { List<int> numbers = new List<int> { 5 }; int singleElement = numbers.SingleOrDefault(); Console.WriteLine($"The single element is: {singleElement}"); // Output: The single element is: 5 } }

Example 2: Empty sequence

using System; using System.Collections.Generic; using System.Linq; public class Example { public static void Main(string[] args) { List<int> emptyList = new List<int>(); int defaultElement = emptyList.SingleOrDefault(); Console.WriteLine($"The default element is: {defaultElement}"); // Output: The default element is: 0 } }

Example 3: Sequence with multiple elements (throws exception)

using System; using System.Collections.Generic; using System.Linq; public class Example { public static void Main(string[] args) { List<int> multipleElements = new List<int> { 1, 2, 3 }; try { int element = multipleElements.SingleOrDefault(); } catch (InvalidOperationException ex) { Console.WriteLine($"Caught expected exception: {ex.Message}"); // Output: Caught expected exception: Sequence contains more than one element. } } }