Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# Linq Last() Method
The LINQ Last() method in C# returns the last element from a sequence. It throws an exception if the sequence is empty, making it suitable when you are certain the collection contains elements.
Syntax
Following is the syntax for the Last() method −
public static TSource Last<TSource>(this IEnumerable<TSource> source); public static TSource Last<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
Parameters
-
source − The sequence to return the last element from.
-
predicate − (Optional) A function to test each element for a condition.
Return Value
Returns the last element in the sequence that satisfies the condition. Throws InvalidOperationException if no element is found.
Using Last() on Arrays
Example
using System;
using System.Linq;
class Demo {
static void Main() {
int[] val = { 10, 20, 30, 40 };
// getting last element
int last_num = val.Last();
Console.WriteLine("Last element: " + last_num);
}
}
The output of the above code is −
Last element: 40
Using Last() with Predicate
Example
using System;
using System.Linq;
class Demo {
static void Main() {
int[] numbers = { 2, 5, 8, 12, 15, 18, 20 };
// get last even number
int lastEven = numbers.Last(x => x % 2 == 0);
Console.WriteLine("Last even number: " + lastEven);
// get last number greater than 10
int lastGreater = numbers.Last(x => x > 10);
Console.WriteLine("Last number > 10: " + lastGreater);
}
}
The output of the above code is −
Last even number: 20 Last number > 10: 20
Using Last() with Lists
Example
using System;
using System.Collections.Generic;
using System.Linq;
class Demo {
static void Main() {
List<string> names = new List<string> { "Alice", "Bob", "Charlie", "David" };
// get last name
string lastName = names.Last();
Console.WriteLine("Last name: " + lastName);
// get last name starting with 'C'
string lastWithC = names.Last(name => name.StartsWith("C"));
Console.WriteLine("Last name starting with C: " + lastWithC);
}
}
The output of the above code is −
Last name: David Last name starting with C: Charlie
Last() vs LastOrDefault() Comparison
| Last() | LastOrDefault() |
|---|---|
| Throws exception if sequence is empty | Returns default value if sequence is empty |
| Use when you're certain elements exist | Use when sequence might be empty |
| Better performance (no null checking) | Safer for uncertain data |
Conclusion
The LINQ Last() method efficiently retrieves the last element from any sequence. Use Last() when you're certain the collection contains elements, or LastOrDefault() when the collection might be empty to avoid exceptions.
