Sud*_*dha 22 c# ienumerable add
我有一个这样的调查员
IEnumerable<System.Windows.Documents.FixedPage> page;
Run Code Online (Sandbox Code Playgroud)
如何添加页面(例如: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 });
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果你知道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都可能不会期望这样的集合被修改.