How to add a range of items to an IList?

mohsen dorparasti picture mohsen dorparasti · Oct 31, 2012 · Viewed 77.3k times · Source

There is no AddRange() method for IList<T>.

How can I add a list of items to an IList<T> without iterating through the items and using the Add() method?

Answer

BlackjacketMack picture BlackjacketMack · Oct 13, 2015

If you look at the C# source code for List<T>, I think List<T>.AddRange() has optimizations that a simple loop doesn't address. So, an extension method should simply check to see if the IList<T> is a List<T>, and if so use its native AddRange().

Poking around the source code, you see the .NET folks do similar things in their own LINQ extensions for things like .ToList() (if it is a list, cast it... otherwise create it).

public static class IListExtension
{
    public static void AddRange<T>(this IList<T> list, IEnumerable<T> items)
    {
        if (list == null) throw new ArgumentNullException(nameof(list));
        if (items == null) throw new ArgumentNullException(nameof(items));

        if (list is List<T> asList)
        {
            asList.AddRange(items);
        }
        else
        {
            foreach (var item in items)
            {
                list.Add(item);
            }
        }
    }
}