我试图实现搜索功能,但遇到问题时,有些字段未由用户填写。Linq跳过查询,如果字符串为空
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返回任何内容并只能当两个字段填写。我曾尝试更换& &与||但是它会得到结果,即使其中一个搜索项不在数据库中。
有没有办法做到这一点,除了Filtering out null values in a linq search
你有什么反对*在linq搜索过滤出空值*? –
@Gert我没有什么反对过滤空值,我只是希望有一种方法可以在一个语句中执行,而不是多个if语句。 – Question
组合查询的优点是SQL语句可以更小并且不包含不必要的元素。 –