AddRange to a Collection
Try casting to List in the extension method before running the loop. That way you can take advantage of the performance of List.AddRange.
public static void AddRange<T>(this ICollection<T> destination,
IEnumerable<T> source)
{
List<T> list = destination as List<T>;
if (list != null)
{
list.AddRange(source);
}
else
{
foreach (T item in source)
{
destination.Add(item);
}
}
}
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>
.
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, Lippert's opinion on ForEach.