简体   繁体   English

Linq查询表列列表

[英]Linq query table column list

Hi I am trying to output a list of items from a table over linq to a dropdown list 嗨,我正在尝试通过linq将表中的项目列表输出到下拉列表中

I am getting an error on the linq query: Cannot implicitly convert generic.list<string> to generic.List<locations> 我在linq查询上遇到错误: Cannot implicitly convert generic.list<string> to generic.List<locations>

Can someone help please? 有人可以帮忙吗? Thanks in advance. 提前致谢。

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;

}

You are selecting a single column select a.Name and then you are trying to store the result of ToList to List<Locations> . 您选择一个列,然后select a.Name ,然后尝试将ToList的结果存储到List<Locations> Your current query would probably result in List<string> which is not assignable to List<Locations> 您当前的查询可能会导致List<string>不能分配给List<Locations>

You can fix that by selecting select a 您可以通过选择select a

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

You also don't need locations.ToList(); 您也不需要locations.ToList(); in your code, since locations is already a list. 在您的代码中,因为locations已经是一个列表。 That is just redundant and you are not even assigning the result of ToList to any other field. 那只是多余的,您甚至没有将ToList的结果分配给任何其他字段。

Edit: You need to set DataTextField and DataValueField property of your DropDownList as well like: 编辑:您需要设置DropDownList DataTextFieldDataValueField属性,例如:

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

If you just want to show names and your selected value would be name as well then you can do: 如果您只想显示名称,并且您选择的值也将是名称,则可以执行以下操作:

 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;

Not really sure why you need to create ddlLocation inside your code, You can create that in ASPX code and just do the binding in code behind. 不太确定为什么需要在代码内创建ddlLocation ,可以在ASPX代码中创建它,然后在后面的代码中进行绑定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM