[英]cannot convert from 'System.Collections.Generic.IEnumerable' to System.Collections.Generic.IEnumerable<string>
I am trying to store a list of multiple values from an object and store it in a dropdownlist by iterating through a loop. 我试图存储一个对象的多个值的列表,并通过循环遍历将其存储在dropdownlist中。
ddlCountries.Items.AddRange((from country in countries
select new List<string> {
country.Name,
country.Slug,
country.Iso
})).ToList();
However I get this error message with the select keyword: 但是我收到带有select关键字的错误消息:
Argument 1: cannot convert from 'System.Collections.Generic.IEnumerable>' to 'System.Web.UI.WebControls.ListItem[]'
参数1:无法从“ System.Collections.Generic.IEnumerable>”转换为“ System.Web.UI.WebControls.ListItem []”
Originally I tested to make sure it can retrieves values from the list using ListItem: 最初,我进行测试以确保它可以使用ListItem从列表中检索值:
ddlCountries.Items.AddRange((from country in countries
select new ListItem(country.Name, country.Slug))
.ToArray<ListItem>());
This works perfectly fine, however I needed to retrieve an additional field (country.iso). 这工作得很好,但是我需要检索其他字段(country.iso)。 I have searched the forums for a solution but I'm having a difficult time finding ways to solve this issue.
我已经在论坛上搜索了解决方案,但是我很难找到解决此问题的方法。 Any help on this would be much appreciated.
任何帮助,将不胜感激。
Well, seeing as the ListItem
class contains only Text
and Value
, you need some way of joining country.Slug
and country.Iso
into a single string value. 好吧,看到
ListItem
类仅包含Text
和Value
,您需要某种方式将country.Slug
和country.Iso
连接到单个字符串值中。
ddlCountries.Items.AddRange((from country in countries
select new ListItem(
country.Name,
country.Slug + "," + country.Iso))
.ToArray());
This will make it so that you are still generating a ListItem[]
instead of a List<List<string>>
. 这样可以使您仍在生成
ListItem[]
而不是List<List<string>>
。
You could try Anonymous Types 您可以尝试匿名类型
var src = from country in countries.AsEnumerable()
select
name = country.Name,
slug = country.Slug,
iso = country.Name + " " + country.slug
ddlCountries.dataSource = src.AsQueryable();
ddlCountries.DataBind();
List expects only one String per item in the List. 列表期望列表中的每个项目只有一个字符串。 Your new type has three fields.
您的新类型包含三个字段。 You could instead try this:
您可以尝试以下方法:
ddlCountries.Items.AddRange( ( from country in countries select new { country.Name, country.Slug, country.Iso } ).ToList() );
But then, why do you need to create a List? 但是,为什么您需要创建一个列表? Have you tried binding the query directly as the datasource to your drop-down-list?
您是否尝试过将查询直接作为数据源绑定到下拉列表? You could then define which field (Name for example) as the Visible field, and Slug/Iso as the Value Field - which is something that you would have to do even now.
然后,您可以将哪个字段(例如Name)定义为Visible字段,并将Slug / Iso定义为Value字段-这是您现在必须要做的事情。
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.