What is the difference between `First()`, `FirstOrDefault()`, `Single()`, and `SingleOrDefault()`?

4 minintermediate.NETLINQcollections

Quick Answer

`First()` returns the first matching element and throws if there are none; `FirstOrDefault()` returns the default (e.g., null/0) instead of throwing. `Single()` expects exactly one match and throws if there are zero or more than one; `SingleOrDefault()` allows zero (returns default) but still throws on more than one. Use `Single*` to assert uniqueness and `First*` when you just want the first of possibly many.

Detailed Answer

These methods retrieve elements from a collection but differ in their expectations and error handling:

First()

  • Returns the first element
  • Throws InvalidOperationException if sequence is empty
  • Use when you expect at least one element

FirstOrDefault()

  • Returns the first element or default value (null for reference types, 0 for numbers)
  • Never throws exception for empty sequences
  • Use when the sequence might be empty

Single()

  • Returns the only element
  • Throws if sequence is empty OR has more than one element
  • Use when you expect exactly one element

SingleOrDefault()

  • Returns the only element or default value
  • Throws if sequence has more than one element (but not if empty)
  • Use when you expect zero or one element
var numbers = new List { 1, 2, 3, 4, 5 };

// First() - returns 1
var first = numbers.First();

// FirstOrDefault() - returns 1, or 0 if empty
var firstOrDefault = numbers.FirstOrDefault();

// Single() - throws exception (more than one element)
var single = numbers.Single(); // InvalidOperationException!

// With predicate
var firstEven = numbers.First(n => n % 2 == 0); // returns 2
var singleFive = numbers.Single(n => n == 5); // returns 5

// Empty sequence
var empty = new List();
// empty.First(); // throws InvalidOperationException
var result = empty.FirstOrDefault(); // returns 0

Related Resources