LINQ Interview Question #144
How do you write LINQ queries that handle null values safely?
Advanced LINQ, Practical Problems & Senior Interview Scenarios Senior Advanced
Quick Interview Answer
Null handling depends on whether the query executes in memory or through a provider. In LINQ to Objects, normal C# null rules apply. Null-conditional and null-coalescing operators can be useful where appropriate.
Detailed Explanation
Null handling depends on whether the query executes in memory or through a provider. In LINQ to Objects, normal C# null rules apply. Null-conditional and null-coalescing operators can be useful where appropriate.
With IQueryable, only expressions supported by the provider can be translated. Database null semantics can also differ from ordinary C# behavior, so important queries should be tested against the actual provider.
Code Example
var names = customers
.Select(c => c.Name ?? "Unknown");
var lengths = customers
.AsEnumerable()
.Select(c => c.Name?.Length ?? 0);