LastOrDefault Examples
This page was last reviewed on Sep 21, 2023.
Dot Net Perls
LastOrDefault, Last. LastOrDefault 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.
C# method info. 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.
int Array
And The third call yields the value 3 because 3 is the final odd value in the source array.
Odd, Even
Info The argument to the third LastOrDefault call is a predicate delegate instance. It is specified as a lambda expression.
Tip The 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
Last. 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.
Detail We demonstrate the Last extension method with a Predicate represented as a lambda expression.
Note The lambda specifies that only odd numbers are accepted. The modulo expression must not return 0.
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
Internals. How does the Last extension work? It determines if the collection type implements IList. The IList interface is implemented by arrays, Lists, and others.
And Suppose Last() is called on a IList. In this case, it uses the last index and returns the last element.
But For other IEnumerable instances, the Last implementation loops through the whole collection.
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 21, 2023 (edit).
© 2007-2024 Sam Allen.