C# Interview Question #45

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

LINQ & Querying Mid-Level Intermediate

Quick Interview Answer

First returns the first matching element and throws an exception if no element exists. FirstOrDefault returns the first matching element or the default value when no element exists.

Detailed Explanation

First returns the first matching element and throws an exception if no element exists. FirstOrDefault returns the first matching element or the default value when no element exists.

Single expects exactly one matching element and throws if there are zero or more than one. SingleOrDefault allows zero matches but throws if more than one match exists.

Use FirstOrDefault when zero or many possible records are acceptable but only the first is needed. Use Single or SingleOrDefault when uniqueness is an important business or data invariant.

Code Example

var product = products.FirstOrDefault(p => p.Id == id);

var user = users.SingleOrDefault(u => u.Email == email);