LINQ Interview Question #46
What does Last do in LINQ?
Filtering, Projection, Ordering & Element Operators Mid-Level Intermediate
Quick Interview Answer
Last returns the final element of a sequence, or the final element satisfying a predicate. It throws if no matching element exists.
Detailed Explanation
Last returns the final element of a sequence, or the final element satisfying a predicate. It throws if no matching element exists.
Its efficiency depends on the source and provider. For database queries, explicitly ordering by the relevant key and selecting the first row is often clearer because the concept of 'last' requires a defined ordering.
Code Example
var lastNumber = numbers.Last();
var lastEven =
numbers.Last(n => n % 2 == 0);