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

时间:2012-08-25 06:40:44

标签: c# linq

我使用国家/地区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'。 '哪里'找不到。考虑   明确指定范围变量'row'的类型。

2 个答案:

答案 0 :(得分:1)

您说您正在尝试使用给定国家/地区的状态名称填充DropDownList,看起来该逻辑位于您的foreach循环中。看起来你的foreach循环也在做很多不必要的工作。

当它真正只需要找到其中一个国家/地区名称时,它会遍历所有国家/地区名称。然后它再次遍历寻找状态的国家名称。

您应该能够抛弃整个foreach循环,而是使用它:

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

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

答案 1 :(得分:0)

尝试更改:

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