C# 无法从“System.Collections.Generic.IEnumerable”转换为System.Collections.Generic.IEnumerable
我试图存储一个对象中多个值的列表,并通过循环将其存储在dropdownlist中C# 无法从“System.Collections.Generic.IEnumerable”转换为System.Collections.Generic.IEnumerable,c#,.net,linq,C#,.net,Linq,我试图存储一个对象中多个值的列表,并通过循环将其存储在dropdownlist中 ddlCountries.Items.AddRange((from country in countries select new List<string> { country.Name, country.Slug,
ddlCountries.Items.AddRange((from country in countries
select new List<string> {
country.Name,
country.Slug,
country.Iso
})).ToList();
但是,我收到带有select关键字的错误消息:
参数1:无法从“System.Collections.Generic.IEnumerable>”转换为“System.Web.UI.WebControl.ListItem[]”
最初,我进行了测试,以确保它可以使用ListItem从列表中检索值:
ddlCountries.Items.AddRange((from country in countries
select new ListItem(country.Name, country.Slug))
.ToArray<ListItem>());
这工作得非常好,但是我需要检索一个额外的字段country.iso。我在论坛上搜索了一个解决方案,但我很难找到解决这个问题的方法。如果您在这方面有任何帮助,我们将不胜感激。鉴于ListItem类只包含文本和值,您需要某种方式将country.Slug和country.Iso合并为一个字符串值
ddlCountries.Items.AddRange((from country in countries
select new ListItem(
country.Name,
country.Slug + "," + country.Iso))
.ToArray());
这将使您仍然生成ListItem[],而不是列表。列表中每个项目只需要一个字符串。您的新类型有三个字段。您可以尝试以下方法: ddlCountries.Items.AddRange( ( from country in countries select new { country.Name, country.Slug, country.Iso } ).ToList() ); 但是,为什么需要创建一个列表呢?您是否尝试过将查询作为数据源直接绑定到下拉列表中?然后,您可以定义哪个字段名,例如作为可见字段,Slug/Iso作为值字段,这是您现在必须做的事情 希望这有帮助。你可以试试
什么类型的物品?System.Web.UI.WebControl.ListItem[]?我认为代码:select new List{country.Name,country.Slug,country.Iso}是错误的,您试图将对象添加到列表中如果是,那么您试图将IEnumerable添加到列表项`.@jophyjob我认为您是对的,应该是select new ListItem{country.Name,country.Slug,country.Iso}我猜。@NikolaiSamteladze是的。Items是一个System.Web.UI.WebControl.ListItem[]我不确定您是否可以将匿名对象添加到ListItem对象的Location中。如果每个字段都单独存储,这将是理想的,但它给出错误:无法使用集合初始值设定项初始化类型“System.Web.UI.WebControl.ListItem”,因为它未实现“System.Collections.IEnumerable”。我的错误。我忘了AddRange需要一个对象[]。正确的方法是将LINQ查询作为DropDownList控件的数据源。并映射正确映射的显示字段和值字段。
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();