简体   繁体   中英

linq to sql query with checkboxes where condition combination

if 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();**
                }

if chkAus and chkNz are checked

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

The condition on linq query changes as the checkboxes are checked.

where cc.Code.Contains("AU") || cc.Code.Contains("NZ")

I have nearly 10 checkboxes, and got stuck on how to write that many conditions. Any help please.

for example if there is chkUS : then the combination with chkAus,chkNz,chkUS checkboxes the linq query would change.

where cc.Code.Contains("AU") || cc.Code.Contains("NZ") || cc.Code.Contains("US")

Put all of them in a list and then do a 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();

Create a list of selected checkboxes first. Like this.

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

And then modify your linq query to check whether this list contains the code or not, I mean reversing the comparison is an answer. Make sure you remove if condition for this linq query.

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

This will fix your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM