Sobes.tech
Junior — Middle

What is the result returned by the LastOrDefault method if there is no matching element in the collection?

sobes.tech AI

Answer from AI

The LastOrDefault method in C# returns the last element of a sequence that satisfies a condition, or the default value for the type if no such element is found.

If no matching element exists in the collection:

  • For reference types, it returns null.
  • For value types, it returns the default value (e.g., 0 for int, false for bool).

Example:

var numbers = new List<int> {1, 2, 3};
int result = numbers.LastOrDefault(n => n > 5); // result will be 0, as there are no elements > 5

string[] words = {"apple", "banana"};
string word = words.LastOrDefault(w => w.StartsWith("z")); // word will be null
What is the result returned by the LastOrDefault… - sobes.tech