FirstOrDefault returning Unexpected Value
.net, c#, linq
Solution
You appear to misunderstand how `DefaultIfEmpty` works.
`list.DefaultIfEmpty(1)` returns a singleton sequence containing `1` if the source collection (`list`) is empty. Since `list` is not empty, this has no effect and the source sequence is returned.
As a result, your query is effectively the same as:
int result = list.FirstOrDefault(i => i > 5);
The default of `int` is `0` so `FirstOrDefault` returns `0` if the condition is not met, which it is not since `list` contains no elements greater than 5.
You can get the behaviour you want using:
int result = list.Cast<int?>().FirstOrDefault(i => i > 5) ?? 1;
Problem
When I set a default value if the set is empty and call `.FirstOrDefault()` with a condition that isn't met I'm not getting my default value, but the type's default value: ``` int[] list = { 1, 2, 3, 4, 5 }; Console.WriteLine(list.DefaultIfEmpty(1).FirstOrDefault(i => i == 4)); // Outputs 4, as expected Console.WriteLine(list.DefaultIfEmpty(1).FirstOrDefault(i => i > 5)); // Outputs 0, why?? ``` This seems unintuitive since I'm setting `.DefaultIfEmpty()` to 1. Why doesn't this output a 1?