Linq到SQL查询与复选框的条件组合



如果checkbox chkAus checked:

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为例:然后结合 chkUS,chkNz,chkUS复选框,linq查询将改变。
where cc.Code.Contains("AU") || cc.Code.Contains("NZ") || cc.Code.Contains("US")

将它们放到一个列表中,然后执行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();

首先创建一个选中复选框的列表。这样的。

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();

相关内容

  • 没有找到相关文章