Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to SQL and Null strings, how do I use Contains?

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,

like image 600
Oakcool Avatar asked Jun 10 '09 17:06

Oakcool


People also ask

How do you handle NULL values in LINQ query?

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 !=

Can LINQ return NULL?

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.

Is NULL SQL in LINQ?

NULL in SQL means, "value absent, will match any comparison", whereas null in . NET means "no object, comparing against null will always yield false".


2 Answers

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>() 
like image 71
Yuliy Avatar answered Sep 18 '22 11:09

Yuliy


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).

like image 28
driis Avatar answered Sep 18 '22 11:09

driis