I have an enumerator like this
IEnumerable<System.Windows.Documents.FixedPage> page;
How can I add a page (eg: D:\newfile.txt) to it? I have tried Add
, Append
, Concat
etc But nothing worked for me.
I have an enumerator like this
IEnumerable<System.Windows.Documents.FixedPage> page;
How can I add a page (eg: D:\newfile.txt) to it? I have tried Add
, Append
, Concat
etc But nothing worked for me.
Try
or
Yes, it is possible
It is possible to concatenate sequences (IEnumerables) together and assign the concatenated result to a new sequence. (You cannot change the original sequence.)
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.The following code demonstrates:
You cannot add elements to
IEnumerable<T>
, since it does not support addition operations. You either have to use an implementation ofICollection<T>
, or cast theIEnumerable<T>
toICollection<T>
if possible.If the cast is impossible, use for instance
You can do it like this:
The latter will almost guarantee that you have a collection that is modifiable. It is possible, though, when using cast, to successfully get the collection, but all modification operations to throw
NotSupportedException
. This is so for read-only collections. In such cases the approach with the constructor is the only option.The
ICollection<T>
interface implementsIEnumerable<T>
, so you can usepageCollection
wherever you are currently usingpage
.IEnumerable<T>
does not contain a way to modify the collection.You will need to implement either
ICollection<T>
orIList<T>
as these contain an Add and Remove functions.If you have an idea of what the original type of the IEnumerable is, you can modify it...
This outputs:
Change the foreach statement to iterate over
stringList2
, orstringEnumerable
, you'll get the same thing.Reflection might be useful to determine the real type of the IEnumerable.
This probably isn't a good practice, though... Whatever gave you the IEnumerable is probably not expecting the collection to be modified that way.
IEnumerable<T>
is a readonly interface. You should use anIList<T>
instead, which provides methods for adding and removing items.