Methods

First()/FirstOrDefault() vs Single()/SingleOrDefault()

These methods are used to retrieve a single element from a sequence.

The main difference between these methods is in how they handle cases where there are multiple matching elements in the sequence.

Single() / SingleOrDefault()First() / FirstOrDefault()

If there are multiple matching elements, Single()/SingleOrDefault() will throw an exception.

If there are multiple matching elements, First()/FirstOrDefault() will only return the first one.

Single / SingleOrDefault is useful for cases where you know there should only be one matching element, and you want to ensure that the query doesn't return multiple results or no results at all.

In general, FirstOrDefault() may be faster because it returns as soon as it finds the first matching element in the sequence, whereas SingleOrDefault() checks to ensure that there is only one matching element and will continue to search the entire sequence even after finding a match.

Example

  • If there are no matching elements

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

// Throws an exception because there are no matching element in the list
Console.WriteLine(numbers.Single(n => n % 2 == 0));
Console.WriteLine(numbers.First(n => n % 2 == 0));

// Returns 0 (default for int)
Console.WriteLine(numbers.SingleOrDefault(n => n % 2 == 0));
Console.WriteLine(numbers.FirstOrDefault(n => n % 2 == 0));
  • If there are multiple matching elements

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

// Throws an exception because there are multiple matching element (2, 4) in the list
Console.WriteLine(numbers.Single(n => n % 2 == 0));
Console.WriteLine(numbers.SingleOrDefault(n => n % 2 == 0));

// Returns 2 (first matching element)
Console.WriteLine(numbers.First(n => n % 2 == 0));
Console.WriteLine(numbers.FirstOrDefault(n => n % 2 == 0));

Conclusion

  • Use FirstOrDefault if you don't care how many items there are or when you can't afford checking uniqueness (e.g. in a very large collection). When you check uniqueness on adding the items to the collection, it might be too expensive to check it again when searching for those items.

  • Use SingleOrDefault if you don't have to care about performance too much and want to make sure that the assumption of a single item is clear to the reader and checked at runtime.

Last updated