c# - FirstOrDefault returning Unexpected Value -


when set default value if set empty , call .firstordefault() condition isn't met i'm not getting default value, type's default value:

int[] list = { 1, 2, 3, 4, 5 }; console.writeline(list.defaultifempty(1).firstordefault(i => == 4)); // outputs 4, expected console.writeline(list.defaultifempty(1).firstordefault(i => > 5));  // outputs 0, why?? 

this seems unintuitive since i'm setting .defaultifempty() 1. why doesn't output 1?

you appear misunderstand how defaultifempty works.

list.defaultifempty(1) returns singleton sequence containing 1 if source collection (list) empty. since list not empty, has no effect , source sequence returned.

as result, query same as:

int result = list.firstordefault(i => > 5); 

the default of int 0 firstordefault returns 0 if condition not met, not since list contains no elements greater 5.

you can behaviour want using:

int result = list.cast<int?>().firstordefault(i => > 5) ?? 1; 

Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -