添加到IEnumerable的代码
我有一个像这样的调查员
IEnumerable page;
如何添加页面(例如:D:\ newfile.txt)? 我试过Add
, Append
, Concat
等但是没有什么对我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 {"One", "Two", "Three"}; IEnumerable originalSequence = stringList; var newSequence = originalSequence.Concat("Four"); foreach (var text in newSequence) { Console.WriteLine(text); // Prints "One" "Two" "Three" "Four". } } } public static class EnumerableExt { /// Concatenates a scalar to a sequence. /// The type of elements in the sequence. /// a sequence. /// The scalar item to concatenate to the sequence. /// A sequence which has the specified item appended to it. /// /// 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. /// public static IEnumerable Concat (this IEnumerable sequence, T item) { return sequence.Concat(new[] { item }); } } }
IEnumerable
不包含修改集合的方法。
您需要实现ICollection
或IList
因为它们包含添加和删除function。
如果你知道IEnumerable的原始类型是什么,你可以修改它……
List stringList = new List (); stringList.Add("One"); stringList.Add("Two"); IEnumerable stringEnumerable = stringList.AsEnumerable(); List stringList2 = stringEnumerable as List ; if (stringList2 != null) stringList2.Add("Three"); foreach (var s in stringList) Console.WriteLine(s);
这输出:
One Two Three
更改foreach语句以迭代stringList2
或stringEnumerable
,你会得到相同的东西。
reflection可能有助于确定IEnumerable的实际类型。
这可能不是一个好习惯,但是……无论是什么给你IEnumerable都可能不会期望这样的集合被修改。
IEnumerable
是一个只读接口。 您应该使用IList
,它提供了添加和删除项目的方法。
IEnumerable
是不可变的。 您无法添加项目,也无法删除项目。
System.Collections.Generic
的类返回此接口,因此您可以迭代集合中包含的项。
来自MSDN
Exposes the enumerator, which supports a simple iteration over a collection of a specified type.
请参阅此处获取MSDN参考。
尝试
IEnumerable page = new List(your items list here)
要么
IList page = new List(1); page.Add(your item Here);
您无法向IEnumerable
添加元素,因为它不支持添加操作。 您必须使用ICollection
,或者如果可能,将IEnumerable
为ICollection
。
IEnumerable page; .... ICollection pageCollection = (ICollection) page
如果演员阵容不可能,请使用例如
ICollection pageCollection = new List(page);
你可以这样做:
ICollection pageCollection = (page as ICollection) ?? new List(page);
后者几乎可以保证你有一个可修改的集合。 但是,使用强制转换可以成功获取集合,但所有修改操作都可能抛出NotSupportedException
。 对于只读集合,这是如此。 在这种情况下,使用构造函数的方法是唯一的选择。
ICollection
接口实现IEnumerable
,因此您可以在当前使用page
任何地方使用pageCollection
。