2

我有以下代码:

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

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

我试图使用 contentTypes.Add(

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

4

5 回答 5

2

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

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

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

于 2013-06-21T16:09:17.677 回答
1

您可以将新值连接到 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 结尾

于 2013-06-21T16:13:27.403 回答
0

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

于 2013-06-21T16:06:41.443 回答
0

尝试这个 -

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

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

于 2013-06-21T16:07:35.653 回答
0

首先,您不能IList.AddIEnumerable<T>. 所以你需要创建一个新的集合。

您正在选择匿名类型,用于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 
于 2013-06-21T16:10:57.340 回答