Linq查询表列列表

时间:2014-02-28 14:04:26

标签: c# asp.net .net linq

您好我正在尝试将表格中的项目列表通过linq输出到下拉列表

我在linq查询中收到错误:Cannot implicitly convert generic.list<string> to generic.List<locations>

有人可以帮忙吗?提前谢谢。

public static void getlocation()
{

    DataClasses_AbintegroDataContext dc = new DataClasses_AbintegroDataContext();

    List<Location> locations = (
        from a 
            in dc.Locations 
        select a.Name).ToList();

    DropDownList ddLocation = new DropDownList();

    locations.ToList();

    ddLocation.DataSource = locations;
    ddLocation.DataBind();

    ddLocation.SelectedIndex = 0;

}

1 个答案:

答案 0 :(得分:1)

您选择的是一列select a.Name,然后您尝试将ToList的结果存储到List<Locations>。您当前的查询可能会导致List<string>无法分配给List<Locations>

您可以选择select a

来解决这个问题
List<Location> locations = (
        from a in dc.Locations 
        select a).ToList();

您的代码中也不需要locations.ToList();,因为locations已经是一个列表。这只是多余的,您甚至没有将ToList的结果分配给任何其他字段。

修改 您需要设置DropDownList的{​​{3}}和DataTextField属性,以及:

ddLocation.DataValueField = "ID"; //Whatever you need the ID to be when selected
ddlLocation.DataTextField = "Name";

如果您只是想显示姓名,而您选择的值也是姓名,那么您可以这样做:

 DataClasses_AbintegroDataContext dc = new DataClasses_AbintegroDataContext();

    List<string> locations = (
        from a in dc.Locations 
        select a.Name).ToList();

    DropDownList ddLocation = new DropDownList();

    ddLocation.DataSource = locations;
    ddLocation.DataBind();
    ddLocation.SelectedIndex = 0;

不确定为什么需要在代码中创建ddlLocation,您可以在ASPX代码中创建它,然后在代码中进行绑定。