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?
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);
The main difference between List and IList in C# is that List is a class that represents a list of objects which can be accessed by index while IList is an interface that represents a collection of objects which can be accessed by index.
IList<string> strings = new List<string>(); The preceeding line of code will work, but you will only have the members of IList available to you instead of the full set from whatever class you initialize.
In C# IList interface is an interface that belongs to the collection module where we can access each element by index. Or we can say that it is a collection of objects that are used to access each element individually with the help of an index. It is of both generic and non-generic types.
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); } } } }
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With