代码增加了IEnumerable [英] Code for adding to IEnumerable

查看:102
本文介绍了代码增加了IEnumerable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样一个枚举

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



我如何添加一个页面(例如:D:\\\
ewfile.txt)呢?我曾尝试添加追加的毗连等,但没有为我工作。

How can I add a page (eg: D:\newfile.txt) to it? I have tried Add, Append, Concat etc But nothing worked for me.

推荐答案

是,有可能

是可能的串联在一起序列(IEnumerables)和连接后的结果分配给一个新的序列。 (您不能改变原来的顺序。)

It is possible to concatenate sequences (IEnumerables) together and assign the concatenated result to a new sequence. (You cannot change the original sequence.)

内置的 Enumerable.Concat() 只会串连另一个序列;然而,很容易编写一个扩展方法,可以让您连接一个标量序列

The built-in Enumerable.Concat() will only concatenate another sequence; however, it is easy to write an extension method that will let you concatenate a scalar to a sequence.

下面的代码演示:

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 });
        }
    }
}

这篇关于代码增加了IEnumerable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆