Both First() and FirstOrDefault() are used to retrieve the first element from a collection, but they behave differently when no matching element is found.
First()
Returns the first element in the collection that matches a given condition.
Throws an exception (InvalidOperationException) if no element is found.
Example-
find the first even number in the list,
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 firstEven = numbers.First(n => n % 2 == 0);
Console.WriteLine("First Even Number: " + firstEven);
// Output: First Even Number: 8
}
}
Example (Throws Exception)
List<int> numbers = new List<int> { 1, 3, 5, 7 };
int firstEven = numbers.First(n => n % 2 == 0); // No even number exist.
// Throws: InvalidOperationException: "Sequence contains no matching element"
FirstOrDefault()
Returns the first 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-
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 firstEven = numbers.FirstOrDefault(n => n % 2 == 0);
Console.WriteLine("First Even Number: " + firstEven);
// Output: First Even Number: 0 (if no even number exists)
// Example with Strings
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
string result = names.FirstOrDefault(n => n.StartsWith("Z"));
Console.WriteLine(result == null ? "No match found" : result);
// Output: No match found
}
}
When to Use What?
When you are sure that at least one matching element exists, use First().
When no matching element exists, use FirstOrDefault() (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.
First() vs FirstOrDefault() in LINQ (C#)
Both First() and FirstOrDefault() are used to retrieve the first element from a collection, but they behave differently when no matching element is found.
First()
InvalidOperationException) if no element is found.Example-
find the first even number in the list,
Example (Throws Exception)
FirstOrDefault()
nullfor reference types,0for numeric types) if no element is found.Example-
When to Use What?
Also, Read: LINQ Aggregate functions