When querying a list of positive numbers using SingleOrDefault()
, how can I return null, or a custom value like -1, when a number isn't found in the list, instead of the type's default value (0 in this case)?
If you have a Query that returns a empty set then ToList returns null. You would probably expect it to return an empty list (Count = 0), which is the case when using data providers for SQL Server.
in conclusion no, it won't return null since null can't say sequence contains no elements it will always say object reference not set to an instance of an object ;) Save this answer.
FirstOrDefault() returns the default value (null) if there is no result data and you can see the result in the following screen.
You can use DefaultIfEmpty
to specify a custom default value for an empty collection:
var value = numbers.Where(MyFilter)
.DefaultIfEmpty(-1) //or any other default value you want
.Single(); //OrDefault not needed; DefaultIfEmpty ensures there is an item
You could use:
var first = theIntegers
.Cast<int?>()
.SingleOrDefault(i => i == theValue) ?? valueIfNotFound;
This works by casting the items to a Nullable<int>
, then using the null-coalescing operator to return the value you choose if null
was returned (ie: not found).
Note this will throw if you have more than one matching item. If you don't want that behavior, use FirstOrDefault
instead of SingleOrDefault
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With