Summary: in this tutorial, you’ll learn how to use the LINQ Last() method to find the last element in a sequence that satisfies a specified condition.
Introduction to the LINQ Last() method
The LINQ Last() method returns the last element in a sequence that satisfies a condition.
Here’s the syntax of the Last() method:
public static TSource Last<TSource>(
this IEnumerable<TSource> source
);Code language: C# (cs)In this syntax:
TSourceis the type of elements in thesourcesequence.sourceis the input sequence with the typeIEnumerable<T>.
The method returns the last element of the source sequence.
If the source is null, the method will throw an ArgumentNullException. Also, if the source is empty, the method will throw an InvalidOperationException.
If you want to find the last element that satisfies a condition, you can use an overload of the Last() method like this:
public static TSource Last<TSource>(
this IEnumerable<TSource> source,
Func<TSource,bool> predicate
);Code language: C# (cs)In this syntax, the predicate is a function that tests each element for a condition.
The method throws an InvalidOperationException if it couldn’t find any element that satisfies the condition.
Generally, the method throws an InvalidOperationException if the source is empty or no element satisfies a condition. To avoid the exception, you can use the LastOrDefault() method.
The LastOrDefault() method returns the last element of a sequence. If it could not find any element that satisfied a condition, it returns a default value.
LINQ Last() method examples
Let’s take some examples of using the LINQ Last() method.
1) Using LINQ Last() method to with a specified condition
The following example demonstrates how to use the Last() method to find the last even number in a list of numbers:
using static System.Console;
List<int> numbers = new() { 1, 7, 2, 8, 6, 9 };
int lastEvenNumber = numbers.Last(n => n % 2 == 0);
WriteLine($"The last even number is: {lastEvenNumber}");Code language: C# (cs)Output:
6In this example, the Last() method returns/ the last even number of the numbers list because of the condition in the lambda expression:
n => n % 2 == 0Code language: C# (cs)2) Using LINQ LastOrDefault() method to handle exceptions
If no element in a sequence satisfies a condition, the Last() method throws an exception. To avoid it, you can use the LastOrDefault() method instead. For example:
using static System.Console;
List<int> numbers = new() { 1, 3, 5 };
int lastEvenNumber = numbers.LastOrDefault(n => n % 2 == 0);
WriteLine($"The last even number is: {lastEvenNumber}");Code language: C# (cs)Output:
The last even number is: 0Code language: C# (cs)In this example, the numbers list has only odd numbers. Therefore, the LastOrDefault() method returns a default value of an integer, which is zero.
Summary
- Use LINQ
Last()method to find the last element of a sequence that satisfies a specified condition.