如果字符串为 Null,Linq 跳过查询

Linq skip query if string is Null

我正在尝试实现搜索功能,但是 运行 遇到一些问题,因为某些字段没有被用户填写。

string country = searchCountry.Text.ToLower();
string state = searchState.Text.ToLower();

var searchLocation= (from h in db.Locations where (!string.IsNullOrWhiteSpace(country) ? h.Country.ToLower().Contains(country):false)
              && (!string.IsNullOrWhiteSpace(state) ? h.State.ToLower().Contains(state) : false)
              select h);

问题是,当其中一个字符串为空时,searchLocation returns 什么都没有,只有在两个字段都填写时才有效。我尝试用 || 替换 &&但它会得到结果,即使其中一个搜索词不在数据库中。

除了Filtering out null values in a linq search

还有什么方法可以做到这一点

我相信你想多了。只需在搜索前验证字段:

string country = searchCountry.Text.ToLower();
string state = searchState.Text.ToLower();

if(string.IsNullOrWhitespace(state) || string.IsNullOrWhitespace(country))
{
   //MessageBox.Show...
   return;
}

var searchLocation= //query with validated fields

在尝试对其执行操作之前验证您的输入是一个很好的主意。而且它使您的代码比将两者结合起来更具可读性。

这将 return 国家/地区为空或匹配且州为空或匹配的任何位置。

var searchLocation= (from h in db.Locations
                     where (string.IsNullOrWhiteSpace(country) || h.Country.ToLower().Contains(country))
                           && (string.IsNullOrWhiteSpace(state) || h.State.ToLower().Contains(state))
                     select h);

对您想放入和取出的东西进行更多描述会有所帮助,但这对我来说似乎合乎逻辑。

这两个字段都是可选的,但它会过滤结果以包含与所有(一个或两个)填写的字段相匹配的任何内容。

当然,如果您 运行 这没有任何过滤器,它将 return 所有位置。因此,如果您向数据库发出请求,请记住这一点。如果这是所需的行为,那么预先将所有数据拉入列表可能是有意义的,而不是每次键入任何内容时都进行查询。