如果属性不为 NULL,我有这个 Linq 语句可以成功构建列表
results.AddRange(m_CTS.Entity.Where(x => x.Property.Contains(search)).ToList());
但是,如果 x.property 为 null 那么它会出错,所以我想尝试检查它是否为 null,如果它不为 null,则继续构建列表。
我试过了,
results.AddRange(m_CTS.Entity.Where(x => x.Property == null ? "" : x.Property.Contains(search)).ToList());
但这也有错误,我做错了什么?
提前致谢
最佳答案
您应该像这样检查 null
:
x.Property != null && x.Property.Contains(search)
Where
需要一个返回 bool
的语句,但您的第一个表达式返回 string
而另一个返回 bool
.所以它无法编译。
&&
之所以起作用是因为short-circuiting .如果 x.Property != null
计算结果为 false,则不会计算第二个表达式,您也不会得到异常。
关于c# - LINQ 在生成 ToList() 时检查字符串属性是否为 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26295206/