LINQ Interview Question #43

What does Single do in LINQ?

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

Quick Interview Answer

Single returns the only element in a sequence and throws if the sequence contains zero elements or more than one element. The predicate overload similarly requires exactly one match.

Detailed Explanation

Single returns the only element in a sequence and throws if the sequence contains zero elements or more than one element. The predicate overload similarly requires exactly one match.

Single expresses a stronger invariant than First: the data is expected to contain exactly one matching element.

Code Example

var settings = configurations
    .Single(c => c.Key == "SiteName");