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?:
var CatA = new Cat();
var CatB = new Cat();
IEnumerable<Cat> cats = new[]{ CatA };
var catList = cats.ToList();
catList.Add(CatB));
cats = catList;
var CatA = new Cat();
var CatB = new Cat();
IEnumerable<Cat> cats = new[]{ CatA };
var catList = cats.ToList();
catList.Add(CatB));
cats = catList;
What I want to do is something like this:
var CatA = new Cat();
var CatB = new Cat();
IEnumerable<Cat> cats = new[]{ CatA };
cats.ToList().Add(CatB));
var CatA = new Cat();
var CatB = new Cat();
IEnumerable<Cat> cats = new[]{ CatA };
cats.ToList().Add(CatB));
But ToList() makes a copy of the IEnumerable cats, and CatB is placed into the copy, instead of the IEnumerable cats.
7 Replies
Anton
Anton3y ago
Use the Concat Linq method
christoffer_tornell
Hah, speaking of Cats. Thanks. I'll try it out
333fred
333fred3y ago
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
Anton
Anton3y ago
yeah, but note that it does not copy the collection it only makes a new iterator object
mindhardt
mindhardt3y ago
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
333fred
333fred3y ago
Yes
MODiX
MODiX3y ago
Orannis#3333
REPL Result: Failure
IList<int> test = new int[0];
test.Add(1);
IList<int> test = new int[0];
test.Add(1);
Exception: NotSupportedException
- Collection was of a fixed size.
- Collection was of a fixed size.
Compile: 482.422ms | Execution: 23.648ms | React with ❌ to remove this embed.
Want results from more Discord servers?
Add your server