c# - How to safely .ToLower().Contains() on possible null property
问题描述
private Expression<Func<ProductDto, bool>> FilterData(ProductRequest searchQuery)
{
string searchString = !string.IsNullOrEmpty(searchQuery.SearchString)
? searchQuery.SearchString.ToLower()
: string.Empty;
return f => ((f.ProductName.ToLower().Contains(searchString))
|| (f.ProductParentName.ToLower().Contains(searchString)));
}
Sometimes ProductName
or ProductParentName
are null so my application crashes.
I've tried using C# 6.0 feature null conditional operator so I wrote something like this:
return f => ((f.ProductName?.ToLower().Contains(searchString))
|| (f.ProductParentName?.ToLower().Contains(searchString)));
But than I got message :
operator || cannot be applied to operands of type
'bool'
and'bool?'
How could I ensure could will execute even if some props are null here?
Thanks
Cheers
解决方案
更新:不可能在表达式树 lambda 中使用空传播运算符(我无法使用它们来工作ToLower
)。您可以使用以下代码重构为StringComparison.OrdinalIgnoreCase
不区分大小写的比较:
return f => (f.ProductName != null)
? (f.ProductName.Contains(searchString, StringComparison.OrdinalIgnoreCase)
|| f.ProductParentName.Contains(searchString, StringComparison.OrdinalIgnoreCase) )
: false;
原始答案
您可以将其与空合并运算符 ( ??
) 结合使用。
return f => ( (f.ProductName?.ToLower().Contains(searchString) ?? false)
|| (f.ProductParentName?.ToLower().Contains(searchString) ?? false));
f.ProductName?.ToLower()
使用返回when is的空条件运算符 ( ) ,因此您需要返回一个默认值,这是空合并运算符提供的值。.?
null
ProductName
null
推荐阅读
- python - 如何在没有 tts 读取的情况下使用 discord.py 发送消息?
- java - 使用 IntentService 和 PendingIntent 接收后台位置更新
- redis - 将 redis-rs 与 actix-web 一起使用
- mysql - 遵循说明后未创建 mysql docker 容器
- reactjs - 在 SetState 中响应循环
- javascript - 我是否必须加载 60 种字体才能在网站中支持 60 种语言?
- javascript - const funcName = (args) => { }; 有什么区别?和 const funcName = (args) => ( );?
- ios - 如何在选择器参数Swift之后添加函数参数
- php - PHP反转一个字节并打印它
- c++ - 如果派生类对象调用基类函数,会修改哪个类的静态变量?