Clean way of adding elements to IEnumerable
Is there a good way of adding an element to an IEnumerable without having to create a copy of the collection as such?:
What I want to do is something like this:
But ToList() makes a copy of the IEnumerable cats, and CatB is placed into the copy, instead of the IEnumerable cats.
7 Replies
Use the
Concat
Linq methodHah, speaking of Cats. Thanks. I'll try it out
Why are you not just starting with a
List
?
And to be clear, Concat
isn't going to do what you want either
Concat
produces a new enumerable, which returns the contents of the first enumerable, then the contents of the added elements
You cannot add elements to an IEnumerable
yeah, but note that it does not copy the collection
it only makes a new iterator object
The purpose of IEnumerable is just to assure iterability, if you want to be able to add thing then IList
Wait, array also implements IList, donnit?
iirc Array is IList but throws exceptions upon adding so am unsure
Yes
Orannis#3333
REPL Result: Failure
Exception: NotSupportedException
Compile: 482.422ms | Execution: 23.648ms | React with ❌ to remove this embed.