LINQ Interview Question #47
What does LastOrDefault do?
Filtering, Projection, Ordering & Element Operators Mid-Level Intermediate
Quick Interview Answer
LastOrDefault returns the final matching element or the default value if no element exists. Like Last, its meaning depends on the sequence's order.
Detailed Explanation
LastOrDefault returns the final matching element or the default value if no element exists. Like Last, its meaning depends on the sequence's order.
When querying a database, define the desired ordering explicitly rather than relying on an unspecified natural row order.
Code Example
var lastActive = users
.LastOrDefault(u => u.IsActive);