【问题标题】:cannot convert from 'System.Collections.Generic.IEnumerable' to System.Collections.Generic.IEnumerable<string>无法从 'System.Collections.Generic.IEnumerable' 转换为 System.Collections.Generic.IEnumerable<string>
【发布时间】:2015-07-27 20:08:13
【问题描述】:

我正在尝试存储来自一个对象的多个值的列表,并通过循环遍历将其存储在下拉列表中。

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.WebControls.ListItem[]'

最初我测试以确保它可以使用 ListItem 从列表中检索值:

ddlCountries.Items.AddRange((from country in countries
                                     select new ListItem(country.Name, country.Slug))
                                     .ToArray<ListItem>());

这工作得很好,但是我需要检索一个额外的字段 (country.iso)。我已经在论坛中搜索了解决方案,但我很难找到解决此问题的方法。对此的任何帮助将不胜感激。

【问题讨论】:

  • ddlCountries.Items 是什么类型? System.Web.UI.WebControls.ListItem[]?
  • 我认为代码:select new List { country.Name,country.Slug, country.Iso} 是错误的,您正在尝试将对象添加到 List
  • 如果是这样,那么您正在尝试将IEnumerable&lt;List&lt;string&gt;&gt; 添加到 ListItem` 的数组中。
  • @jophyjob 我想你是对的,我猜应该是select new ListItem { country.Name,country.Slug, country.Iso }
  • @NikolaiSamteladze 是的,ddlCountries.Items 是 System.Web.UI.WebControls.ListItem[]

标签: c# .net linq


【解决方案1】:

好吧,既然ListItem 类只包含TextValue,您需要某种方式将country.Slugcountry.Iso 连接成一个字符串值。

ddlCountries.Items.AddRange((from country in countries
                             select new ListItem(
                                 country.Name,
                                 country.Slug + "," + country.Iso))
                             .ToArray());

这将使您仍然生成ListItem[] 而不是List&lt;List&lt;string&gt;&gt;

【讨论】:

    【解决方案2】:

    你可以试试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();
    

    【讨论】:

      【解决方案3】:

      List 要求 List 中的每个项目只有一个字符串。您的新类型包含三个字段。你可以试试这个:

      ddlCountries.Items.AddRange( (来自国家的国家 选择新的{国家.名称,国家.Slug,国家.Iso} ).ToList() );

      但是,为什么你需要创建一个列表呢?您是否尝试将查询直接作为数据源绑定到下拉列表?然后,您可以将哪个字段(例如名称)定义为 Visible 字段,并将 Slug/Iso 定义为值字段 - 这是您现在必须要做的事情。

      希望这会有所帮助。

      【讨论】:

      • 我不确定您是否可以将匿名对象添加到 ListItem 对象的 locclection 中。
      • 这将是理想的让每个字段分别存储,但它会给出错误:无法使用集合初始化程序初始化类型“System.Web.UI.WebControls.ListItem”,因为它没有实现“系统” .Collections.IEnumerable'。
      • 我的错。我忘记了 AddRange 需要一个对象 []。正确的方法是将 LINQ 查询作为 DropDownList 控件的数据源。并映射正确映射的显示字段和值字段。
      猜你喜欢
      • 2013-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多