LINQ Interview Question #42
What is the difference between First and FirstOrDefault?
Filtering, Projection, Ordering & Element Operators Mid-Level Intermediate
Quick Interview Answer
First throws an exception when no element exists, while FirstOrDefault returns the default value. The choice should reflect the semantics of the application.
Detailed Explanation
First throws an exception when no element exists, while FirstOrDefault returns the default value. The choice should reflect the semantics of the application.
Use First when absence violates an expectation. Use FirstOrDefault when an empty result is a normal possibility that the caller is prepared to handle.
Code Example
var requiredAdmin =
users.First(u => u.IsAdmin);
var optionalUser =
users.FirstOrDefault(u => u.Email == email);