C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
And: The third call yields the value 3 because 3 is the final odd value in the source array.
Odd, EvenInfo: The argument to the third LastOrDefault call is a predicate delegate instance. It is specified as a lambda expression.
LambdaPredicateTip: The LastOrDefault method will never throw an exception on a non-null collection reference. It will return the default value.
NullC# program that uses LastOrDefault method
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
3
Lambda: 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.
ModuloC# program that uses Last extension
using System;
using System.Linq;
class Program
{
static void Main()
{
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);
}
}
Output
6
5
But: For other IEnumerable instances, the Last implementation loops through the whole collection.