[英]How can I use the conditional null operator to check for null string?
I'm trying to execute the LINQ to objects query as follows: 我试图执行LINQ到对象查询,如下所示:
var c1 = allCustomers
.Where(x => x.CompanyName.Replace("'", "").StartsWith(searchText))
.ToList();
This works fine as long as CompanyName is not null. 只要CompanyName不为null,就可以正常工作。
So, I thought this seems like the perfect place for the new null conditional operator! 因此,我认为对于新的空条件运算符来说,这似乎是理想的选择! Just change to:
只需更改为:
var c1 = allCustomers
.Where(x => x.CompanyName?.Replace("'", "").StartsWith(searchText))
.ToList();
and everything should work! 一切都会正常!
Instead, I get the error: 相反,我得到了错误:
Cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?)
I'm not quite sure how to accomplish what I want here. 我不太确定如何在这里完成我想要的。 How would I use the null conditional in this scenario?
在这种情况下,我将如何使用null条件?
You need a coalesce operator to convert the tri-state to a proper boolean. 您需要合并运算符将三态转换为适当的布尔值。
var c1 = allCustomers
.Where(x => x.CompanyName?.Replace("'", "").StartsWith(searchText) ?? false)
.ToList();
I call bool?
我叫
bool?
a tri-state because it can have three values: true
, false
and null
; 三态,因为它可以具有三个值:
true
, false
和null
; therefore, converting bool?
因此,转换
bool?
to bool
is a narrowing conversion that requires explicit treatment. 转化为
bool
是一种狭窄的转化,需要进行明确的处理。
you need more question marks! 您需要更多问号! i think you need null coalescing as well, since
x.CompanyName?.Replace
could now also return null. 我认为您也需要空合并,因为
x.CompanyName?.Replace
现在也可以返回空。
(x.CompanyName?.Replace("'", "") ?? string.Empty).StartsWith(searchText))
the ?? string.empty
?? string.empty
?? string.empty
forces that to be a non-null string, which now supports .startswith
?? string.empty
强制将其设置为非null字符串,该字符串现在支持.startswith
Use ??
使用
??
operator like: 运算子,例如:
Where(x => x.CompanyName?.Replace("'", "").StartsWith(searchText) ?? false)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.