A coworker asked me today how to add a range to a collection. He has a class that inherits from Collection
. There\'s a get-only property of that type t
No, this seems perfectly reasonable. There is a List<T>.AddRange() method that basically does just this, but requires your collection to be a concrete List<T>
.
Here is a bit more advanced/production-ready version:
public static class CollectionExtensions
{
public static TCol AddRange<TCol, TItem>(this TCol destination, IEnumerable<TItem> source)
where TCol : ICollection<TItem>
{
if(destination == null) throw new ArgumentNullException(nameof(destination));
if(source == null) throw new ArgumentNullException(nameof(source));
// don't cast to IList to prevent recursion
if (destination is List<TItem> list)
{
list.AddRange(source);
return destination;
}
foreach (var item in source)
{
destination.Add(item);
}
return destination;
}
}
You could add your IEnumerable range to a list then set the ICollection = to the list.
IEnumerable<T> source;
List<item> list = new List<item>();
list.AddRange(source);
ICollection<item> destination = list;
Or you can just make an ICollection extension like this:
public static ICollection<T> AddRange<T>(this ICollection<T> @this, IEnumerable<T> items)
{
foreach(var item in items)
{
@this.Add(item);
}
return @this;
}
Using it would be just like using it on a list:
collectionA.AddRange(IEnumerable<object> items);
Since .NET4.5
if you want one-liner you can use System.Collections.Generic ForEach.
source.ForEach(o => destination.Add(o));
or even shorter as
source.ForEach(destination.Add);
Performance-wise it's the same as for each loop (syntactic sugar).
Also don't try assigning it like
var x = source.ForEach(destination.Add)
cause ForEach
is void.
Edit: Copied from comments, Lipert's opinion on ForEach
The C5 Generic Collections Library classes all support the AddRange
method. C5 has a much more robust interface that actually exposes all of the features of its underlying implementations and is interface-compatible with the System.Collections.Generic
ICollection
and IList
interfaces, meaning that C5
's collections can be easily substituted as the underlying implementation.