在LINQ中使用国家DDL填充状态DDL



我正在使用国家/地区DDL 填充状态DDL

public static IEnumerable bindcountry()
{
    var countries = from c in getdata().Descendants(("country"))
                    orderby (string)c.Element("name")
                    select (string)c.Element("name");
    return countries;
}
public List<string> GetStatesByCountry(string CountryName)
{
    var query = from user in getdata().Descendants("country")
                where user.Element("name").Value == CountryName
                from t in user.Descendants("text")
                select t.Value;
    return query.ToList();
}
foreach (var VARIABLE in ProfileMasterDAL.bindcountry())
{
    if (VARIABLE.ToString().Contains(DropDownList1.SelectedItem.Text))
    {
        var query = from row in ProfileMasterDAL.bindcountry()
                    where row.(ProfileMasterDAL.GetStatesByCountrys(DropDownList1.SelectedItem.Text))
                    select row;
        DropDownList2.DataSource = query;
        DropDownList2.DataBind();
    }
}

问题是我无法定义WHERE子句,在这里我得到了一个错误:

找不到源类型的查询模式的实现未找到"System.Collections.IEnumerable"。"Where"。考虑显式指定范围变量"row"的类型。

您说您正试图用给定国家/地区的州名填充DropDownList,而该逻辑似乎在您的foreach循环中。看起来foreach循环也在做很多不必要的工作。

当它真的只需要找到其中一个国家名称时,它会迭代所有的国家名称。然后,它还会再次遍历国家名称,查找各州。

您应该能够抛出整个foreach循环,转而使用以下内容:

var query = ProfileMasterDAL.GetStatesByCountry(DropDownList1.SelectedItem.Text);
DropDownList2.DataSource = query;   
DropDownList2.DataBind();   

您的GetStatesByCountry方法只返回属于传入国家/地区名称的州,因此您应该能够调用该名称,只获取这些州的名称,然后将它们分配给DropDownList

尝试更改:

public static IEnumerable bindcountry()     
{           
var countries = from c in getdata().Descendants(("country")) orderby (string)c.Element("name") select (string)c.Element("name");
return countries ;       
}

public static IList<string> bindcountry()     
{           
var countries = from c in getdata().Descendants(("country")) orderby (string)c.Element("name") select (string)c.Element("name");        
return countries.ToList() ;       
} 

最新更新