Enumerable.LastOrDefault Method
System.Linq
Summary
Returns the last element of a sequence, or a default value if the sequence contains no elements.
public static TSource LastOrDefault<TSource>(this IEnumerable<TSource> source);
public static TSource LastOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
Parameters
source
An IEnumerable<TSource> to return the last element from.
predicate
A function to test each element for a condition.
Returns
TSource
The last element in the sequence that satisfies the predicate, or the default value for the type of the element if no such element is found.
Generic Type Parameters
TSource
The type of the elements of source.
Remarks
If the source sequence is empty, the method returns the default value for type TSource.
The default value is 0 for numeric types, false
for Boolean, null
for reference types, and an empty slot for value types.
The overload with a predicate returns the last element that satisfies the condition. If no element satisfies the condition, it returns the default value for type TSource.
This method uses deferred execution.
Examples
// Example 1: LastOrDefault without a predicate
int[] numbers = { 1, 2, 3, 4, 5 };
int last = numbers.LastOrDefault();
// last will be 5
int[] emptyNumbers = { };
int lastOfEmpty = emptyNumbers.LastOrDefault();
// lastOfEmpty will be 0 (default for int)
string[] names = { "Alice", "Bob", "Charlie" };
string lastOrNull = names.LastOrDefault();
// lastOrNull will be "Charlie"
string[] emptyNames = { };
string lastOfEmptyNull = emptyNames.LastOrDefault();
// lastOfEmptyNull will be null (default for string)
// Example 2: LastOrDefault with a predicate
int[] scores = { 10, 25, 30, 45, 50, 60, 75 };
int lastScoreAbove40 = scores.LastOrDefault(score => score > 40);
// lastScoreAbove40 will be 75
int lastScoreAbove100 = scores.LastOrDefault(score => score > 100);
// lastScoreAbove100 will be 0 (default for int)