【问题标题】:Populating states DDL using country DDL in LINQ在 LINQ 中使用国家 DDL 填充国家 DDL
【发布时间】:2012-08-25 06:40:43
【问题描述】:

我正在使用国家 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 子句和 equals 在这里我得到一个错误:

找不到源类型的查询模式的实现 'System.Collections.IEnumerable'。 '哪里' 没有找到。考虑 显式指定范围变量“行”的类型。

【问题讨论】:

    标签: c# linq


    【解决方案1】:

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

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

    您应该能够丢弃整个 foreach 循环,而改用这个:

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

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

    【讨论】:

    • 但在这段代码之前我像 DropDownList1.SelectedValue = Session["country"].ToString();并且国家 DDL 值没有更改为另一个国家我该如何更改它?
    【解决方案2】:

    尝试改变:

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

    【讨论】:

    • 当我在查询中这样做时,它说 Enumeration 没有产生任何结果,并且状态 DDL 为空。
    • 更改查询时是否会抛出异常?
    • 当我调试我得到的代码时,枚举在查询中没有产生任何结果。
    • 那说明你的DB里没有数据或者没有正确设置。
    • 我有 XML 中的值,当我检查 profilemaster.bincountry() 和 ProfileMasterDAL.GetStatesByCountrys(DropDownList1.SelectedItem.Text) 我得到了值,但我不知道为什么查询没有结果
    猜你喜欢
    • 2012-11-04
    • 2018-02-15
    • 1970-01-01
    • 1970-01-01
    • 2013-09-16
    • 2021-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多