Junior — Middle
Can you explain what the LastOrDefault method means in LINQ?
sobes.tech AI
Answer from AI
The LastOrDefault method in LINQ returns the last element of a sequence that satisfies a specified condition, or the default value for the type if no such elements exist.
If no condition is specified, it returns the last element of the entire sequence or the default value if the sequence is empty.
Example:
int[] numbers = {1, 2, 3, 4, 5};
int lastEven = numbers.LastOrDefault(n => n % 2 == 0); // returns 4
int lastGreaterThanTen = numbers.LastOrDefault(n => n > 10); // returns 0 (default for int)
string[] words = {};
string lastWord = words.LastOrDefault(); // returns null (default for string)
Thus, LastOrDefault is safe to use when there is no guarantee that the sequence contains suitable elements, and it helps avoid the InvalidOperationException that occurs when using Last on an empty sequence.