110

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?

6 Answers 6

105

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);
            }
        }
    }
}
6
  • 6
    From the optimization point of view, you are actually casting list to List<T> two times here. One of which could be optimized away with the as keyword.
    – bashis
    Jun 28, 2016 at 18:04
  • Good call @bashis. I always go back and forth on the cost of a double cast vs. GC cleanup of our new var. But we could indeed do var listCasted = list as List<T>; if(listCasted != null)... Maybe c# 6 declaration expressions will change this pattern: if(myVar.As(out myVarCasted)) myVarCasted...) Jun 29, 2016 at 14:29
  • Can you update the code with the optimization mentioned? I am not as fluent in the newest features yet. @BlackjacketMack
    – user4344677
    Apr 4, 2017 at 13:46
  • 2
    @zuckerthoben - I just ran a test iterating one million iterations using both approaches and there was no difference in performance. So I wouldn't call it an optimization...additionally, it adds a line of code (but reduces a parens casting). Anyhow, I probably would use 'as' these days: var listCasted = list as List<T>; if(listCasted != null){listCasted.AddRange(items);}. Not worth updating the answer IMHO, but good to introduce as a syntactical alternative. Apr 4, 2017 at 14:15
  • 3
    As of now you can do if (list is List<T> castedList) { castedList.AddRange(items); } Jun 18, 2019 at 10:43
76

AddRange is defined on List<T>, not the interface.

You can declare the variable as List<T> instead of IList<T> or cast it to List<T> in order to gain access to AddRange.

((List<myType>)myIList).AddRange(anotherList);

This is not good practice (see comments below), as an IList<T> might not be a List<T>, but some other type that implemented the interface and may very well not have an AddRange method - in such a case, you will only find out when your code throws an exception at runtime.

So, unless you know for certain that the type is indeed a List<T>, you shouldn't try to use AddRange.

One way to do so is by testing the type with the is or as operators (since C# 7).

if(myIList is List<T>)
{
   // can cast and AddRange
}
else
{
   // iterate with Add
}
11
  • 2
    @mohsen.d - If the type is generated, you don't want to change the generated code (as it is liable to be overwritten). Either cast or use LINQ Concat, as @Self_Taught_Programmer answered.
    – Oded
    Oct 31, 2012 at 12:44
  • 2
    @mohsen.d - If it is your code, might as well declare the type as List<T> (or, if this is not a good choice for you, do the cast where you need to AddRange to keep it localized - it is a very low cost operation).
    – Oded
    Oct 31, 2012 at 12:46
  • 58
    No, no, no. The reason this is an IList<T> to begin with is because it may be something else than a List<T> implementation. Write an extension method as shown by BlackjacketMack if you really need an AddRange method. Nov 12, 2015 at 21:55
  • 6
    No idea why this received so many upvotes as it will clearly throw something like InvalidCastException if used on anything other than List<T> (array, for instance).
    – bashis
    Jun 28, 2016 at 18:43
  • 3
    But, casting is not a good idea. It can lead to performance overhead.
    – Gul Ershad
    Mar 30, 2017 at 5:24
27

You could do something like this:

IList<string> oIList1 = new List<string>{"1","2","3"};
IList<string> oIList2 = new List<string>{"4","5","6"};
IList<string> oIList3 = oIList1.Concat(oIList2).ToList();

So, basically you would use the Concat() extension and ToList() to get a similar functionality as AddRange().

Source

1
  • 2
    The problem with your approach is that Enumerable.Concat is implemented by System.Linq.Enumerable and that method's return value is IEnumerable<TSource>, so I believe it shouldn't be cast back to IList<TSource> - it might return something else due to implementation details that we don't know without checking the source code - even though, there's no guarantee it won't change - so special attention must be taken when supporting multiple .NET versions.
    – jweyrich
    Feb 11, 2015 at 16:42
11

You could also write an extension method like this:

internal static class EnumerableHelpers
{
    public static void AddRange<T>(this IList<T> collection, IEnumerable<T> items)
    {
        foreach (var item in items)
        {
            collection.Add(item);
        }
    }
}

Usage:

IList<int> collection = new MyCustomList(); //Or any other IList except for a fixed-size collection like an array
var items = new[] {1, 4, 5, 6, 7};
collection.AddRange(items);

Which is still iterating over items, but you don't have to write the iteration or cast every time you call it.

0
4

Another answer using LINQ, provided the thing you're adding is a List<T> or you are able to call ToList() on it:

IEnumerable<string> toAdd = new string[] {"a", "b", "c"};
IList<string> target = new List<string>();

toAdd.ToList().ForEach(target.Add);
1

IList don't has AddRange() ,but has Concat() which combine yours collection

2
  • 1
    it would be better to add a code sample to make you answer more useful Nov 13, 2021 at 7:15
  • 2
    IList<T>.Concat(IEnumerable<T>) returns the concatenated sequence as an enumerable so leaves the list untouched. That may or may not be the desired result.
    – Manfred
    Apr 18, 2022 at 3:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.