c# - 如何在 C# 中向 IEnumerable 添加元素

标签 c# ienumerable

我有以下代码:

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

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

我试图使用 contentTypes.Add(

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

最佳答案

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

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

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

关于c# - 如何在 C# 中向 IEnumerable 添加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17239662/

相关文章:

c# - 将 guildUserProperties.Mute 设置为 false 时,Bot 不会取消用户静音

c# - 使用 HttpClient 时如何不排除 Content-Type 中的字符集?

c# - 你是把你的计算放在你的 set 上还是 gets 上?

c# - 为什么即使在每次迭代时重新创建查询也会应用多个过滤器

c# - 单击用户控件更新面板内动态按钮上的事件

c# - asp 按钮里面的 Font Awesome

c# - 如何使用c#.net在数据表中搜索一行

linq - 如何在不运行它们的情况下合并两个 Linq IEnumerable<T> 查询?

c# - 奇怪的委托(delegate)引用行为

c# - 如何检查一个列表是否包含另一个列表的所有元素