LINQ Interview Question #44

What does SingleOrDefault do?

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

Quick Interview Answer

SingleOrDefault returns the only matching element or the default value when no element exists, but it still throws if more than one element matches.

Detailed Explanation

SingleOrDefault returns the only matching element or the default value when no element exists, but it still throws if more than one element matches.

It is useful when zero or one result is valid but duplicates indicate a data-integrity or logic problem.

Code Example

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

if (user is null)
{
    // No matching user.
}