C # Extension Method for AddItem for IEnumerable <T>
What is the best way to add an item to an IEnumerable collection using the extension method?
+1
mynkow
source share3 answers
enumerable.Concat(new[]{ objToAdd }) +10
Mehrdad afshari
source shareYou cannot (directly). The purpose of the interface is to display a counter.
Change You will need to convert IEnumerable to another type (e.g. List ) or concatenation to add, which will not add the existing IEnumerable , but concatenate instead of IEnumerable instead.
The only option is to check if it implements any interfaces that you can use to add as IList, ICollection, IDictionary, ILookup, ... and even then you will not be sure that you can add IEnumerable to the existing one.
+1
Jaroslav jandek
source shareI have this in my IEnumerableExtensions class, but I'm not sure if it is too efficient, but I use it very sparingly.
public static IEnumerable<T> Add<T>(this IEnumerable<T> enumerable, T item) { var list = enumerable.ToList(); list.Add(item); return list; } 0
Jamiec
source share