C#C
C#4y ago
13 replies
Christoffer

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;

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));

But ToList() makes a copy of the IEnumerable cats, and CatB is placed into the copy, instead of the IEnumerable cats.
Was this page helpful?