我有一个这样的枚举器
IEnumerable<System.Windows.Documents.FixedPage> page;
如何向其中添加页面(例如:D:\newfile.txt)?我尝试了 Add
、Append
、Concat
等,但对我没有任何效果。
最佳答案
是的,这是可能的
可以将序列 (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/