{TOC}
| Namespace: | System.Linq |
| Assembly: | System.Core.dll |
| Extends: | IEnumerable<T> |
Back to
Standard Query Operator IndexEditIntroduction
The Single operator returns the single element of a sequence.
EditMethod Signatures
// 1 - Get the first and only record
public static TSource Single<TSource>(
this IEnumerable<TSource> source)
// 2 - Gets the only record that passes the predicate function
public static TSource Single<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate)EditExceptions
Throws an ArgumentNullException if
source or
predicate is null.
Throws an InvalidOperationException if
source is empty.
Throws an InvalidOperationException if no records, or more than one record pass the
predicate function.
EditPseudo-code
Overload 1
If
source is null, throw an ArgumentNullException.
If
source is of type
IList.
If there are no elements in source, throw an InvalidOperationException.
If there is more than one element in source, throw an InvalidOperationException.
Return source[0], the first and only element by index position. (performance enhancement).
Else
Iterate over source
If there is no first record in source, throw an InvalidOperationException.
If there is more than one element in source, throw an InvalidOperationException.
Return the current-element (we only ever iterate to the first record).
Overload 2
If
source is null, throw an ArgumentNullException.
If
predicate is null, throw an ArgumentNullException.
Initialize a counter to zero.
Iterate the
source sequence.
If predicate(current element) returns true.
Remember the current element.
Increment the counter by 1.
If counter is zero, throw an InvalidOperationException.
If counter > 1 (more than one element passed the
predicate function), throw an InvalidOperationException.
Return the one and only element that passed the predicate.
EditLoop Count
Overload 1
< 1. If
source is an
IList type, the first element is accessed by index which is very quick, otherwise the first (and second if it exists) is enumerated.
Overload 2
1.
Source is iterated once to find a matching element or to ascertain if there is more than one element that passes the
predicate function.
EditCode Samples
TODO: Needs code sample.