問題描述
這里是查詢
from a in this._addresses
where a.Street.Contains(street) || a.StreetAdditional.Contains(streetAdditional)
select a).ToList<Address>()
如果 where 子句中的兩個屬性都有值,這可以正常工作,但例如,如果 a.StreetAdditional 為空(大多數情況下),我將收到空引用異常.
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?
謝謝,
推薦答案
最明顯的一個:
from a in this._addresses
where (a.Street != null && a.Street.Contains(street)) || (a.StreetAdditional != null && a.StreetAdditional.Contains(streetAdditional))
select a).ToList<Address>()
或者,您可以為 Contains 編寫一個擴展方法,該方法接受空參數而不會出錯.有人可能會說,有這樣的方法不是很好,因為它看起來像一個普通的方法調用,但允許有空值(從而擱置正常的空檢查實踐).
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).
這篇關于LINQ to SQL 和空字符串,我如何使用包含?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!