
LastOrDefault is a helpful method. It finds the last element in your C# collection that matches any condition or a predicate condition. With LastOrDefault you will get either the last matching element or the default value.

This program shows the LastOrDefault method, which is found in the System.Linq namespace. The result is 3 for the first array. For the second array, which is empty, the result is 0 because the default int value is 0. The third call yields the value 3 as well because 3 is the final odd value in the source array.
This C# program uses the LastOrDefault method from System.Linq.
Program that uses LastOrDefault method [C#]
using System;
using System.Linq;
class Program
{
static void Main()
{
// Last or default.
int[] array1 = { 1, 2, 3 };
Console.WriteLine(array1.LastOrDefault());
// Last when there are no elements.
int[] array2 = { };
Console.WriteLine(array2.LastOrDefault());
// Last odd number.
Console.WriteLine(array1.LastOrDefault(element => element % 2 != 0));
}
}
Output
3
0
3Predicate argument. The argument to the third LastOrDefault call is a predicate delegate instance. It is specified as a lambda expression; the right side returns true or false depending on the result of the expression.
Lambda Expression Predicate Type
Exceptions. The LastOrDefault method will never throw an exception on a non-null collection reference. It will return the default value if no last value is found.
Last Extension
Similar to the FirstOrDefault method, the LastOrDefault method is useful for scanning source collections for an element. These methods can be used to develop programs that do not have errors in edge cases, such as empty source collections.
LINQ Examples