简体   繁体   中英

How to select/merge multiple matching result?

I am trying to create a cascading set of drop-down list, country list based upon the region list.

I have created a Dictionary<String, List<String>> in the code behind, which includes a region, country list.

Now on region drop down selection (which is multi select able), I need to select the countries belonging to the particular regions(selected ones) and bind it to the country list.

I am trying this way:

List<string> selectedRegions = (from ListItem item in regionList.Items
                                where item.Selected
                                select item.Text).ToList();

var countryList = (selectedRegions
                          .Where(item => regionToCountry.ContainsKey(item))
                          .Select(item => new { value = regionToCountry[item] }));

countryList.DataSource = countryList.ToList(); 
countryList.DataBind();

The problem is country list gets the result in indexed format like : countryList[0] (contains all the country from region a) countryList[1] from region B.

I need a merged list which I can bind to the dropdown.

Thanks a lot in advance.

Vishal

You can use SelectMany to flatten the List<string> inside the Dictionary<TKey,TValue> .

var countryList =
    regionToCountry.Where(x => selectedRegions.Contains(x.Key))
                   .SelectMany(x => x.Value)
                   .ToList();

Try this:

var countryList = selectedRegions
                          .Where(item => regionToCountry.ContainsKey(item))
                          .SelectMany(item => regionToCountry[item])
                          .ToList();

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