{TOC}
| Namespace: | System.Linq |
| Assembly: | System.Core.dll |
| Extends: | IEnumerable<T> |
Back to
Standard Query Operator IndexEditIntroduction
The First operator returns the first element of a sequence. If you don't want an exception thrown when there is no first elements in the sequence (or no first element that passes the predicate function), use the
FirstOrDefault operator instead.
EditMethod Signatures
// 1 - Return the first element of a sequence.
public static TSource First<TSource>(
this IEnumerable<TSource> source)
// 2 - Return the first element that passes a predicate function in the sequence.
public static TSource First<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate)EditExceptions
Throws an ArgumentNullException if
source or
predicate is null.
Throws an InvalidOperationException if
source has no elements, or no elements pass the predicate function.
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 throw InvalidOperationException.
Return source[0]. (performance optomization)
Else Iterate the
source sequence.
If there is no first element, throw InvalidOperationException.
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.
Throw InvalidOperationException 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.