We want to get first blue car, so need to call FirstOrDefault with appropriate condition:. Application crashes again because of NullReferenceException. It is because there is no yellow car on the list.
Skip to content. FirstOrDefault ;. First is: 3. First is : 3. Clear ;. First is: 0. Otherwise there is no problem with the method idea in question at least. Secondly, accessing members of returned objects is horrible.
It makes locating null pointers a pain and reading the code a pain. For reference types this is null. An int is 0 , a bool is false , and so on. If you want the behaviour you are talking about you need to use DefaultIfEmpty [ docs here ] and supply the default object you want back in the case of an empty sequence. Some use cases may call for this, but with a default value different from null: have a look at this stackoverflow question I asked some while ago, answers to which helped me tremendously afterwards.
It is the stick your head in the sand method. SingleOrDefault can be an acceptable usage. When i find myself needing First or Single i always create extension methods that allow me to do dollarDollarBills.
Is that so? But playing along if children. Any return children. FirstOrDefault returns the default value of the Data Type used if nothing is found, for example in case of integer it would be 0, in case of any Reference type like classes or objects it is NULL.
It depends on what the LINQ query is supposed to return. The Default part of FirstOrDefault means the default of the type being enumerated. DefaultIfEmpty will return the source enumeration if it has elements in it, but if the source enumeration is empty no elements in it. The FirstOrDefault method does not provide a way to specify the default value to return if source is empty. In the second query, there is no element in the sequence that satisfies the condition.
The expected behavior is that it returns the first element in source that satisfies the condition in predicate , or a default value if no element satisfies the condition.
Skip to main content. This browser is no longer supported. Download Microsoft Edge More info. Contents Exit focus mode.
0コメント