LINQ Interview Question #57
What does DefaultIfEmpty do in LINQ?
Joins, Grouping, Set & Quantifier Operators Mid-Level Intermediate
Quick Interview Answer
DefaultIfEmpty returns the source sequence when it contains elements. If the source is empty, it returns a sequence containing one default value.
Detailed Explanation
DefaultIfEmpty returns the source sequence when it contains elements. If the source is empty, it returns a sequence containing one default value.
It is particularly important in the standard LINQ left-outer-join pattern because it ensures the outer record can still produce a result when no inner match exists.
Code Example
var values = Array.Empty<int>();
var result = values.DefaultIfEmpty();
// For int, the sequence contains 0.