首页 > 解决方案 > 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

标签: c#entity-frameworklinqlambda.net-core

解决方案


更新:不可能在表达式树 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的空条件运算符 ( ) ,因此您需要返回一个默认值,这是空合并运算符提供的值。.?nullProductNamenull


推荐阅读