C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
The List resizes to accommodate the inserted elements. InsertRange handles collections that implement IEnumerable.
Example. First, InsertRange is related to the AddRange method, which allows you to add an array or other collection on the end of a List. InsertRange instead inserts the IEnumerable in between existing elements, or at the start.
C# program that uses InsertRange using System; using System.Collections.Generic; class Program { static void Main() { List<int> a = new List<int>(); a.Add(1); a.Add(2); a.Add(5); a.Add(6); // Contains: // 1 // 2 // 5 // 6 int[] b = new int[3]; b[0] = 7; b[1] = 6; b[2] = 7; a.InsertRange(1, b); // Contains: // 1 // 7 [inserted] // 6 [inserted] // 7 [inserted] // 2 // 5 // 6 foreach (int i in a) { Console.WriteLine(i); } } } Output 1 7 6 7 2 5 6
The program populates a new List instance with four integral values in the Main entry point. Next, it creates an array with three more values. Finally, it inserts the array into the List at the second index.
Internals. Here we look inside the base class library in the .NET Framework and see that InsertRange is implemented by using Array.Copy and the CopyTo instance method on arrays. The entire array inside the List will have to be copied.
Here: This example shows the internal code for InsertRange. If the new range fits in the allocated size, the new range is simply copied.
But: Sometimes two Array.Copy calls are needed: one for the elements before, and one for the elements after. A new array is allocated.
InsertRange method body: C# this.EnsureCapacity(this._size + count); if (index < this._size) { Array.Copy(...); } if (this == is2) { Array.Copy(...); Array.Copy(...); } else { T[] array = new T[count]; is2.CopyTo(array, 0); array.CopyTo(...); }
Summary. We looked at the InsertRange method, seeing an example of how you can add an array to a List. We then looked at the algorithmic time complexity of the InsertRange method, seeing that it can be an expensive and slow operation.
Tip: If you have a requirement for inserting elements often, the LinkedList class is faster, as you need to adjust only one reference.