添加到IEnumerable的代码

Sud*_*dha 22 c# ienumerable add

我有一个这样的调查员

IEnumerable<System.Windows.Documents.FixedPage> page;
Run Code Online (Sandbox Code Playgroud)

如何添加页面(例如:D:\newfile.txt)?我已经试过Add,Append,Concat等但没有为我工作.

Mar*_*rst 8

IEnumerable<T> 不包含修改集合的方法.

您将需要实现ICollection<T>IList<T>包含添加和删除功能.


Mat*_*son 7

对的,这是可能的

可以将序列(IEnumerables)连接在一起,并将连接结果分配给新序列.(您无法更改原始序列.)

内置的Enumerable.Concat()只会连接另一个序列; 但是,编写一个扩展方法很容易,它可以让你将标量连接到一个序列.

以下代码演示:

using System;
using System.Collections.Generic;
using System.Linq;

namespace Demo
{
    public class Program
    {
        [STAThread]
        private static void Main()
        {
            var stringList = new List<string> {"One", "Two", "Three"};

            IEnumerable<string> originalSequence = stringList;

            var newSequence = originalSequence.Concat("Four");

            foreach (var text in newSequence)
            {
                Console.WriteLine(text); // Prints "One" "Two" "Three" "Four".
            }
        }
    }

    public static class EnumerableExt
    {
        /// <summary>Concatenates a scalar to a sequence.</summary>
        /// <typeparam name="T">The type of elements in the sequence.</typeparam>
        /// <param name="sequence">a sequence.</param>
        /// <param name="item">The scalar item to concatenate to the sequence.</param>
        /// <returns>A sequence which has the specified item appended to it.</returns>
        /// <remarks>
        /// The standard .Net IEnumerable extensions includes a Concat() operator which concatenates a sequence to another sequence.
        /// However, it does not allow you to concat a scalar to a sequence. This operator provides that ability.
        /// </remarks>

        public static IEnumerable<T> Concat<T>(this IEnumerable<T> sequence, T item)
        {
            return sequence.Concat(new[] { item });
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,它是_possible_,但它**非常低效! (2认同)
  • 只是为了澄清,它确实*不*将项目附加到现有集合,它会创建一个附加该项目的*新序列*. (2认同)

Ste*_*eve 6

如果你知道IEnumerable的原始类型是什么,你可以修改它......

List<string> stringList = new List<string>();
stringList.Add("One");
stringList.Add("Two");
IEnumerable<string> stringEnumerable = stringList.AsEnumerable();
List<string> stringList2 = stringEnumerable as List<string>;

if (stringList2 != null)
    stringList2.Add("Three");

foreach (var s in stringList)
    Console.WriteLine(s);
Run Code Online (Sandbox Code Playgroud)

这输出:

One
Two
Three
Run Code Online (Sandbox Code Playgroud)

将foreach语句更改为迭代stringList2,或者stringEnumerable,您将获得相同的内容.

反射可能有助于确定IEnumerable 的实际类型.

这可能不是一个好习惯,但是......无论是什么给你IEnumerable都可能不会期望这样的集合被修改.

  • 您最好将 stringList2 转换为 ICollection&lt;string&gt; 而不是 List&lt;string&gt;,因为它适用于 List&lt;string&gt; 以及从 ICollection 继承的其他对象。如果 stringList 不是 ICollection&lt;string&gt;,它仍然会失败并且不会添加。 (2认同)

Fre*_*örk 5

IEnumerable<T>是一个只读接口.您应该使用IList<T>替代,它提供添加和删除项目的方法.