{TOC}
| Namespace: | System.Linq |
| Assembly: | System.Core.dll |
| Extends: | IEnumerable<T> |
Back to
Standard Query Operator IndexEditIntroduction
The SingleOrDefault operator returns the single element of a sequence, or a default value if no element is found.
EditMethod Signatures
// 1 - Return the first and only element.
// If there is no elements or more than one, return default(TSource).
public static TSource SingleOrDefault<TSource>(
this IEnumerable<TSource> source)
// 2 - Return the first and only element that passed the predicate function.
// If there is no elements or more than one, return default(TSource).
public static TSource SingleOrDefault<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate)
EditExceptions
Throws an ArgumentNullException if
source or
predicate is null.
EditPseudo-code
Overload 1
If
source is null, throw an ArgumentNullException.
If
source is of type
IList.
If there are no elements in source, return default(TSource);.
If there is more than one element in source, return default(TSource);.
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, return default(TSource);.
If there is more than one element in source, return default(TSource);.
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, return
default(TSource);.
If counter > 1 (more than one element passed the
predicate function), return
default(TSource);.
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
int[] ageMaster = { 11, 21, 31, 41, 51 };
try
{
ageMaster.Single (n => n > 60);
}
catch (Exception ex)
{
ex.Message.Dump ("The Single age > 60");
}
ageMaster.SingleOrDefault (n => n > 50).Dump ("The SingleOrDefault age > 50");
ageMaster.SingleOrDefault (n => n < 10).Dump("The SingleOrDefault age < 10");