FirstOrDefault returns an unexpected value

When I set the default value, if the set is empty and calls .FirstOrDefault() with a condition that is not satisfied, I do not get my default value, but the default value for the type:

 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 as I set .DefaultIfEmpty() to 1. Why doesn't it output 1?

+4
source share
7 answers

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; 
+12
source

This is what you are looking for:

 Console.WriteLine(list.Where(i => i > 5).DefaultIfEmpty(1).First()); 

By placing Where in front of DefaultIfEmpty , an empty collection will return an enumerated element with one element. Then you can use First to get this element.

+9
source

The default value for integer is 0 .

FirstOrDefault returns the first occlusion value or the default, in your case you use int , so it is 0 . If you want an exception, if you don't have an element, try using First(x => x > 5) .

+1
source

FirstOrDefault refers to the value of the default(T) expression, where T is the type of the collection, not the first value of your list. You cannot change this behavior, and you cannot change the default value for a type.

+1
source

FirstOrDefault () Returns int, int is not NULL, so the default value is 0. Check the table of default values ​​on MSDN http://msdn.microsoft.com/en-us/library/83fhsxwc(v=vs.80) .aspx

+1
source

The default value for non-nullable int is 0. Since nothing in your list is> 5, it returns the default value.

+1
source

DefaultIfEmpty does not set a default value. It gives you a list with the same default value if the original list is empty.

0
source

Source: https://habr.com/ru/post/1491942/


All Articles