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

前端 未结 9 1050
别那么骄傲
别那么骄傲 2020-12-14 01:23

Here is the query

from a in this._addresses
where a.Street.Contains(street) || a.StreetAdditional.Contains(streetAdditional)
select a).ToList
(
9条回答
  •  余生分开走
    2020-12-14 01:58

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

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

提交回复
热议问题