Last() and LastOrDefault() both retrieve the last element from a collection, but they behave differently when no matching element is found.
Last()
Returns the last element in the collection that matches a given condition.
Throws an exception (InvalidOperationException) if no matching element is found.
Example-
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 3, 7, 8, 10, 15 };
int lastEven = numbers.Last(n => n % 2 == 0);
Console.WriteLine("Last Even Number: " + lastEven);
// Output: Last Even Number: 10
}
}
LastOrDefault()
Returns the last matching element, or the default value (null for reference types, 0 for numeric types) if no element is found.
Does not throw an exception when no element matches.
Example-
Finding Last Even Number, with Default Handling
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 3, 7, 8, 10, 15 };
int lastEven = numbers.LastOrDefault(n => n % 2 == 0);
Console.WriteLine("Last Even Number: " + lastEven);
// Output: Last Even Number: 10 (if present) or 0 (if no match)
// with string
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
string result = names.LastOrDefault(n => n.StartsWith("Z"));
Console.WriteLine(result == null ? "No match found" : result);
// Output: No match found
}
}
When to use what?
Use Last() when you are sure that at least one matching element exists.
Use LastOrDefault() when no matching element exists (to avoid exceptions).
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Last() vs LastOrDefault() in LINQ (C#)
Last() and LastOrDefault() both retrieve the last element from a collection, but they behave differently when no matching element is found.
Last()
Example-
LastOrDefault()
Example-
Finding Last Even Number, with Default Handling
When to use what?
Also, Read: Explain First(), FirstOrDefault() function in LINQ with C#