Here is the query
from a in this._addresses where a.Street.Contains(street) || a.StreetAdditional.Contains(streetAdditional) select a).ToList<Address>()
if both properties in the where clause have values this works fine, but if for example, a.StreetAdditional is null (Most of the times), I will get a null reference exception.
Is there a work around this?
Thanks,
An object collection such as an IEnumerable<T> can contain elements whose value is null. If a source collection is null or contains an element whose value is null , and your query doesn't handle null values, a NullReferenceException will be thrown when you execute the query. var query1 = from c in categories where c !=
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 ;) Oh, your explanation helps further understanding.
NULL in SQL means, "value absent, will match any comparison", whereas null in . NET means "no object, comparing against null will always yield false".
I'd use the null-coalescing operator...
(from a in this._addresses where (a.Street ?? "").Contains(street) || (a.StreetAdditional ?? "").Contains(streetAdditional) select a).ToList<Address>()
The most obvious one:
from a in this._addresses where (a.Street != null && a.Street.Contains(street)) || (a.StreetAdditional != null && a.StreetAdditional.Contains(streetAdditional)) select a).ToList<Address>()
Alternatively you could write an extension method for Contains that accepts a null argument without error. Some might say that it is not so pretty to have such a method, because it looks like a normal method call, but is allowed for null values (thereby setting aside normal null-checking practices).
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