public static TSource SingleOrDefault<TSource>(IEnumerable<TSource> source)
Returns the only element of a sequence, or a default value if the sequence is empty; by default the default value is null for reference types.
This method throws an InvalidOperationException if there is more than one element in the sequence.
TSource
The single element of the input sequence, or the default value for type TSource if the sequence is empty.
The default value for reference types is null. The default value for value types is 0 if the type is numeric, false if the type is boolean, or null if the type is nullable.
You can use the overload of SingleOrDefault
that accepts a predicate to specify a condition for selecting an element.
using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main()
{
List<int> numbers1 = new List<int> { 5 };
int singleNumber1 = numbers1.SingleOrDefault();
// singleNumber1 is 5
List<int> numbers2 = new List<int>();
int singleNumber2 = numbers2.SingleOrDefault();
// singleNumber2 is 0 (the default for int)
List<string> names1 = new List<string> { "Alice" };
string singleName1 = names1.SingleOrDefault();
// singleName1 is "Alice"
List<string> names2 = new List<string>();
string singleName2 = names2.SingleOrDefault();
// singleName2 is null (the default for string)
List<int> numbers3 = new List<int> { 1, 2, 3 };
try
{
int singleNumber3 = numbers3.SingleOrDefault();
}
catch (InvalidOperationException ex)
{
// ex.Message is "Sequence contains more than one element."
Console.WriteLine(ex.Message);
}
}
}