Short answer: You cannot add elements to IEnumerable<T>
A bit longer explanation:
IEnumerable is an interface that is extremely concerned about the ability to list / repeat a set of elements. This is the sole purpose of IEnumerable . It abstracts any idea of ββhow to store or retrieve enumerated elements (this can be a character string, a list of elements, a stream of bytes or a series of calculation results), so if you have an interface that is IEnumerable , you cannot add elements to it, you can iterate over only the elements it provides.
However, the correct way to add elements to IEnumerable is to return a new IEnumerable with new elements added to the contents of the original.
Also with Linq libraries, you have an extension method that allows you to use your IEnumerable in a List via IEnumerable.ToList() , and you can add items to the list. This may not be the right way.
With the Linq libraries in your namespace, you can do the following:
using System; using System.Collections.Generic; using System.Linq; namespace EnumTester { class Program { static void Main(string[] args) { IEnumerable<string> enum = GetObjectEnumerable(); IEnumerable<string> concatenated = enum.Concat(new List<string> { "concatenated" }); List<string> stringList = concatenated.ToList(); } } }
Rolling tepp
source share