It seems you do not understand how DefaultIfEmpty works.
list.DefaultIfEmpty(1) returns a single sequence containing 1 if the source set ( list ) is empty. Since list not empty, this does not affect the original sequence.
As a result, your request will actually be the same as:
int result = list.FirstOrDefault(i => i > 5);
The default value of int is 0 , so FirstOrDefault returns 0 if the condition is not met, which is not the case, since list does not contain elements greater than 5.
You can get the desired behavior:
int result = list.Cast<int?>().FirstOrDefault(i => i > 5) ?? 1;
source share