LINQ to SQL和空字符串,我怎么使用包含? [英] LINQ to SQL and Null strings, how do I use Contains?

查看:517
本文介绍了LINQ to SQL和空字符串,我怎么使用包含?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是查询

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.

有没有解决此问题?

谢谢,

推荐答案

最明显的:

from a in this._addresses
where (a.Street != null && a.Street.Contains(street)) || (a.StreetAdditional != null && a.StreetAdditional.Contains(streetAdditional))
select a).ToList<Address>()

另外,您可以为包含接受没有错误null参数写的扩展方法。也许有人会说,这不是那么漂亮有这样的方法,因为它看起来像一个正常的方法调用,但允许空值(从而留出空正常检查的做法)。

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和空字符串,我怎么使用包含?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆