{TOC}
| Namespace: | System.Linq |
| Assembly: | System.Core.dll |
| Extends: | IEnumerable<T> |
Back to
Standard Query Operator IndexEditIntroduction
The LastOrDefault operator returns the last element of a sequence, or a default value if no element is found.
EditMethod Signatures
// 1 - Return the last element, or if the source sequence is empty, return default(TSource)
public static TSource LastOrDefault<TSource>(
this IEnumerable<TSource> source)
// 2 - Return the last element that passes the predicate function.
// If there are no elements or no elements pass the predicate, return default(TSource)
public static TSource LastOrDefault<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[count - 1]. (performance optomization)
Else Iterate the
source sequence.
If there is no elements at all return return default(TSource).
If this is the last element, return it as the result.
Overload 2
If
source is null, throw an ArgumentNullException.
If
predicate is null, throw an ArgumentNullException.
Iterate the
source sequence.
If predicate(current element) returns true, remember current element.
If no matching element was found.
Return return default(TSource).
Else
Return the last element that passed 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, Loop count = 1 as the entire sequence is iterated to find the last element.
Overload 2
1. The entire
source sequence is iterated, and the last matching element is returned.
EditCode Samples
TODO: Needs code sample.