Sobes.tech
Junior — Middle

What are the differences between FirstOrDefault and SingleOrDefault methods in LINQ?

sobes.tech AI

Answer from AI

In LINQ, the methods FirstOrDefault and SingleOrDefault are used to select elements from a sequence but have different semantics:

  • FirstOrDefault returns the first element of the sequence if it exists, otherwise it returns the default value (null for reference types).
  • SingleOrDefault returns the single element of the sequence if there is exactly one, otherwise:
    • If there are no elements — it returns the default value.
    • If there are more than one element — it throws an InvalidOperationException.

Example:

var numbers = new List<int> { 1, 2, 3 };

var first = numbers.FirstOrDefault(); // returns 1
var single = numbers.SingleOrDefault(); // throws an exception because there are more than one element

var empty = new List<int>();

var firstEmpty = empty.FirstOrDefault(); // returns 0 (default for int)
var singleEmpty = empty.SingleOrDefault(); // also returns 0

var singleItem = new List<int> { 42 };

var singleValue = singleItem.SingleOrDefault(); // returns 42

Summary:

  • Use FirstOrDefault when you want to get the first element or null if there are no elements.
  • Use SingleOrDefault when you expect exactly one element and want to get an error if there are more than one.