LastOrDefault
, LastLastOrDefault
is a helpful C# method—it finds the last element in a collection that matches a condition. In many cases Last()
does the same thing.
With LastOrDefault()
we get either the last matching element or the default value. Last meanwhile will throw an exception if no element exists.
LastOrDefault
This program shows the LastOrDefault
method. 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.
LastOrDefault
call is a predicate delegate instance. It is specified as a lambda expression.LastOrDefault
method will never throw an exception on a non-null collection reference. It will return the default value.using System; using System.Linq; // 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));3 0 3
This program calls the Last extension method on an array. Last()
is found in System.Linq
and can be used on arrays, Lists, or anything that implements IEnumerable
.
Predicate
represented as a lambda expression.using System; using System.Linq; int[] values = { 1, 2, 3, 4, 5, 6 }; int last = values.Last(); int lastOdd = values.Last(element => element % 2 != 0); Console.WriteLine(last); Console.WriteLine(lastOdd);6 5
How does the Last extension work? It determines if the collection type implements IList
. The IList
interface
is implemented by arrays, Lists, and others.
Last()
is called on a IList
. In this case, it uses the last index and returns the last element.IEnumerable
instances, the Last implementation loops through the whole collection.Last and LastOrDefault
access elements. Last has optimizations for Lists and arrays, but is also effective for other collections. LastOrDefault
, unlike Last, throws no exceptions.