LINQ Interview Question #41
What does FirstOrDefault do?
Filtering, Projection, Ordering & Element Operators Mid-Level Intermediate
Quick Interview Answer
FirstOrDefault returns the first element, or the default value when the sequence contains no matching element. For reference types the default is normally null; for non-nullable value types it is the type's default value.
Detailed Explanation
FirstOrDefault returns the first element, or the default value when the sequence contains no matching element. For reference types the default is normally null; for non-nullable value types it is the type's default value.
The caller should handle the possibility that no element was found. In nullable-aware C# code, this is especially important for reference types.
Code Example
var product = products
.FirstOrDefault(p => p.Id == id);
if (product is null)
{
return NotFound();
}