LINQ Interview Question #45

What is the difference between FirstOrDefault and SingleOrDefault?

Filtering, Projection, Ordering & Element Operators Mid-Level Intermediate

Quick Interview Answer

FirstOrDefault returns the first matching element and does not complain if additional matches exist. SingleOrDefault requires at most one matching element and throws when multiple matches are found.

Detailed Explanation

FirstOrDefault returns the first matching element and does not complain if additional matches exist. SingleOrDefault requires at most one matching element and throws when multiple matches are found.

Use SingleOrDefault when uniqueness is part of the intended invariant. Use FirstOrDefault when any first match is sufficient or uniqueness is not being asserted by the query.

Code Example

var firstLog =
    logs.FirstOrDefault(x => x.UserId == userId);

var uniqueAccount =
    accounts.SingleOrDefault(x => x.AccountNumber == number);