System.Linq.Enumerable.Single()
Defined in: System.Linq.Enumerable
Returns the single element of a sequence, and throws an exception if there is not exactly one element in the sequence.
Syntax
public static TSource Single<TSource>(this IEnumerable<TSource> source);
Parameters
Name | Type | Description |
---|---|---|
source |
IEnumerable<TSource> |
An IEnumerable<TSource> that contains the elements to return a single element from. |
Type Parameters
Name | Description |
---|---|
TSource |
The type of the elements of source . |
Return Value
TSource
The single element of type TSource
in the input sequence.
Exceptions
ArgumentNullException
:source
is null.InvalidOperationException
: The input sequence is empty or contains more than one element.
Examples
Example 1: Getting the single element from a sequence with one element
// Sample code
var numbers = new List<int> { 5 };
var singleNumber = numbers.Single(); // singleNumber will be 5
Example 2: Attempting to get the single element from an empty sequence (throws InvalidOperationException)
// Sample code
var emptyList = new List<int>();
try
{
var result = emptyList.Single();
}
catch (InvalidOperationException ex)
{
// The exception message will indicate that the sequence is empty.
Console.WriteLine(ex.Message);
}
Example 3: Attempting to get the single element from a sequence with multiple elements (throws InvalidOperationException)
// Sample code
var multipleNumbers = new List<int> { 1, 2, 3 };
try
{
var result = multipleNumbers.Single();
}
catch (InvalidOperationException ex)
{
// The exception message will indicate that the sequence contains more than one element.
Console.WriteLine(ex.Message);
}
The Single()
method is useful when you expect a sequence to contain exactly one item. If the sequence contains zero or more than one item, it throws an InvalidOperationException
, which helps you catch unexpected data scenarios.