【问题标题】:How can I add an element to an IEnumerable in C# [duplicate]如何在 C# 中将元素添加到 IEnumerable [重复]
【发布时间】:2013-06-18 20:18:04
【问题描述】:

我有以下代码:

      var contentTypes =
          (
              from contentType in this._contentTypeService.GetContentTypes()
              select new
              {
                  id = contentType.ContentTypeId,
                  name = contentType.Name
              }
          );

如何向 id 为 99 且名称为“All”的 contentTypes 添加另一个元素?

我试图使用 contentTypes.Add(

但智能感知似乎不允许这样做。

【问题讨论】:

  • 您可以将 contentTypes 转换为 List,然后在其上调用 Add 方法。
  • Gemma,您应该在发布新问题之前检查现有的问答。这已在 StackOverflow 上被多次询问,使用的标题几乎与您用于问题的标题相同。

标签: c# ienumerable


【解决方案1】:

如果您使用contentTypes.ToList(),则可以添加到该列表中,但是这样做会创建一个集合的新实例,因此您实际上不会修改源集合。

【讨论】:

    【解决方案2】:

    试试这个 -

    var contentTypes =
              (
                  from contentType in this._contentTypeService.GetContentTypes()
                  select new
                  {
                      id = contentType.ContentTypeId,
                      name = contentType.Name
                  }
              ).ToList();
    

    由于您已将 contentTypes 转换为 List,它应该允许您向其中添加新项目。

    【讨论】:

      【解决方案3】:

      您不能添加到IEnumerable<T>IEnumerable<T>s 代表可以迭代的序列;它们不代表您可以添加到的集合。你可以做的是concatenate 到你的序列的末尾,获得一个新的序列:

      var sequence = contentTypes.Concat(
                         new[] {
                             new { id = 99, name = "All" }
                         }
                     );
      

      现在,如果您遍历sequence,您将首先看到contentTypes 的元素流式传输给您,然后最后的项目将是附加的项目new { id = 99, name = "All" }

      【讨论】:

        【解决方案4】:

        首先,您不能在IEnumerable<T> 上使用IList.Add。所以你需要创建一个新的集合。

        您正在选择匿名类型,请使用Concat 将固定的任何匿名类型添加到您的查询中:

        var allTypes = new[]{new { id = 99, name = "All" }};    // creates a fixed anonymous type as `IEnumerable<T>`
        var contentTypes = from contentType in this._contentTypeService.GetContentTypes()
                           select new
                           {
                               id = contentType.ContentTypeId,
                               name = contentType.Name
                           };
        var result = allTypes.Concat(contentTypes).ToList(); // concat 
        

        【讨论】:

          【解决方案5】:

          您可以将新值连接到 IEnumerable 的末尾。

          var contentTypes =
             (
                from contentType in new[]{new {ContentTypeId = 1, Name="TEST"}}
                select new
                {
                    id = contentType.ContentTypeId,
                    name = contentType.Name
                }
             ).Concat(new[]{new {id = 99, name="All"}});
          

          生成的 IEnumerable 将以 99/All 结尾

          【讨论】:

            猜你喜欢
            • 2017-02-13
            • 2013-08-22
            • 2014-05-26
            • 1970-01-01
            • 1970-01-01
            • 2011-12-02
            • 2019-05-12
            • 2013-01-04
            • 2015-11-20
            相关资源
            最近更新 更多