c# - 添加到 IEnumerable 的代码

标签 c# ienumerable add

我有一个这样的枚举器

IEnumerable<System.Windows.Documents.FixedPage> page;

如何向其中添加页面(例如:D:\newfile.txt)?我尝试了 AddAppendConcat 等,但对我没有任何效果。

最佳答案

是的,这是可能的

可以将序列 (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 });
        }
    }
}

关于c# - 添加到 IEnumerable 的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15760870/

相关文章:

java - AESCrypt 从 Java 到 C#

c# - 没有类型的 IEnumerable 属性

c# - 使用 yield 来推迟 Azure blob 存储调用 - c#

java - 斐波那契数列 : Sum of all numbers

java - 多个 NULL 添加到 Java 中的列表中

c# - 处理拖动时是否可以更改鼠标光标(来自 DragOver 事件)?

c# - OptionalFieldAttribute 真的有效吗?

c# - 我如何知道所有控件何时加载并显示?

c# - 在属性中公开 IEnumerable 是否安全?

c++ - 复合赋值和运算符的区别