I would like to add new iEnumerable object to original one. Can I do this updating original object in extenstion method like following?
public static void AddItems<TSource>(this IEnumerable<TSource> orginalColl,
IEnumerable<TSource> collectionToAdd)
{
foreach (var item in collectionToAdd)
{
orginalColl.ToList<TSource>().Add(item);
}
}
I am calling like this: OrgCollecation.AddItems(newCollection).
But this does not seems to work. Any idea?
An
IEnumerable[<T>]is not intended for adding. You can concatenate (generating a new sequence), but that doesn’t change the original sequence (/list/array/etc). You can do that withEnumerable.Concat, i.e.return orginalColl.Concat(...). But emphasis: this does not update the original collection.What you could do would be to cast to
IList[<T>]or similar, but that would be abusive (and will only work for some scenarios, not all). It won’t work, for example, for anything that is based on an iterator block (or any otherIEnumerable<T>that is not also anIList<T>) – for example it won’t work onsomeSource.Where(predicte).If you expect to change the source, then you should be passing in something like
IList[<T>]. For example:(btw,
AddRangewould be an alternative name for the above, to matchList<T>.AddRange)