如果选中复选框chkAus:
if (chkAus.Checked)
{
vAdvanceSearchResults = (from t in vAdvanceSearchResults
join imp in _bDataContext.Imprints on t.ImprintID equals imp.ID
join cc in _bDataContext.CountryCodes on imp.CountryID equals cc.ID
where cc.Code.Contains("AU")
select t).Distinct();**
}
如果选中chkAus和chkNz
if (chkNz.Checked && chkAus.Checked)
{
vAdvanceSearchResults = (from t in vAdvanceSearchResults
join imp in _bDataContext.Imprints on t.ImprintID equals imp.ID
join cc in _bDataContext.CountryCodes on imp.CountryID equals cc.ID
where cc.Code.Contains("AU") || cc.Code.Contains("NZ")
select t).Distinct();
}
当检查复选框时,linq查询的条件会发生变化。
where cc.Code.Contains("AU") || cc.Code.Contains("NZ")
我有近10个复选框,并且陷入了如何编写这么多条件的问题。 请帮忙。
例如,如果有 chkUS : 然后结合 chkAus,chkNz,chkUS 复选框,linq查询将会改变。
where cc.Code.Contains("AU") || cc.Code.Contains("NZ") || cc.Code.Contains("US")
答案 0 :(得分:3)
将所有这些放入列表中,然后执行if list.contains(cc.Code)
var a = new List<string>(){"AU","NZ","US"};
var linq = (from t in vAdvanceSearchResults
join imp in _bDataContext.Imprints on t.ImprintID equals imp.ID
join cc in _bDataContext.CountryCodes on imp.CountryID equals cc.ID
where a.Contains(cc.Code)
select t).Distinct();
答案 1 :(得分:1)
首先创建所选复选框的列表。像这样。
var selectedCountries = new List<string>();
if (chkAus.Checked) selectedCountries.Add("AU");
if (chkNz.Checked) selectedCountries.Add("NZ");
if (chkUs.Checked) selectedCountries.Add("US");
//... And so on
然后修改您的linq查询以检查此列表是否包含代码,我的意思是反转比较是一个答案。确保删除此linq查询的条件。
vAdvanceSearchResults = (from t in vAdvanceSearchResults
join imp in _bDataContext.Imprints on t.ImprintID equals imp.ID
join cc in _bDataContext.CountryCodes on imp.CountryID equals cc.ID
where selectedCountries.Contains(cc.Code)
select t).Distinct();
这将解决您的问题。