LINQ to SQL and Null strings, how do I use Contains?(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.
有办法解决这个问题吗?
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 和空字符串,我如何使用包含?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:LINQ to SQL 和空字符串,我如何使用包含?


基础教程推荐
- Page.OnAppearing 中的 Xamarin.Forms Page.DisplayAlert 2022-01-01
- C# - 如何列出发布到 ASPX 页面的变量名称和值 2022-01-01
- 我什么时候应该使用 GC.SuppressFinalize()? 2022-01-01
- 创建属性设置器委托 2022-01-01
- 覆盖 Json.Net 中的默认原始类型处理 2022-01-01
- C# - 将浮点数转换为整数...并根据余数更改整数 2022-01-01
- 使用 SED 在 XML 标签之间提取值 2022-01-01
- 当键值未知时反序列化 JSON 2022-01-01
- 从 VB6 迁移到 .NET/.NET Core 的最佳策略或工具 2022-01-01
- 如何使用OpenXML SDK将Excel转换为CSV? 2022-01-01