{TOC}
| Namespace: | System.Linq |
| Assembly: | System.Core.dll |
| Extends: | IEnumerable<T> |
Back to
Standard Query Operator IndexEditIntroduction
The FirstOrDefault operator returns the first element of a sequence, or a default value if no element is found.
EditMethod Signatures
// 1 - Return the first element of a sequence or default(TSource); if empty.
public static TSource FirstOrDefault<TSource>(
this IEnumerable<TSource> source)
// 2 - Return the first element that passes a predicate function in the sequence.
// Return default(TSource) if the sequence is empty.
public static TSource FirstOrDefault<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 the
source sequence implements IList<T>, then
If the source sequence is empty return default(TSource);.
Return source[0]. (performance optomization)
Else Iterate the
source sequence.
If there is no first element, return default(TSource);.
Return the first (current element) element.
Overload 2
If
source is null, throw an ArgumentNullException.
Iterate the
source sequence.
If predicate(current element) returns true, return the current element.
Return
default(TSource); if no elements pass the
predicate function.
EditLoop Count
Overload 1
< 1. If the collection is of type IList, then the first element is accessed by index position which is different depending on the collection implementation. Otherwise, an iterator returns the first element.
Overload 2
< 1. The
source sequence is iterated, and the first matching element is returned.
EditCode Samples
TODO:Needs code sample.