C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
It can replace tedious foreach-loops that repeatedly call Add on List. We can pass any IEnumerable collection to AddRange, not just an array or another List.
Example. We look at the AddRange instance method from the base class library in the C# language on List. This example adds a range at the end of the List using the AddRange method. The term "range" simply means an IEnumerable collection.
Based on: .NET 4 C# program that uses AddRange 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.AddRange(b); // Contains: // 1 // 2 // 5 // 6 // 7 [added] // 6 [added] // 7 [added] foreach (int i in a) { Console.WriteLine(i); } } } Output 1 2 5 6 7 6 7
We see a new List created, and four ints added to it. Then, an array of three elements of the same numeric type is initialized. We then call AddRange as an instance method on List. It receives the array.
Result: It displays seven integers, which are the union of the List itself and the array we added with AddRange.
Internals. I wanted to know how AddRange and its friend InsertRange do in the runtime. I found that AddRange is a wrapper method on top of InsertRange. More information on the implementation of InsertRange is available.
Performance. First, we know that AddRange and InsertRange are internally the same method. Second, we know from the compiled code above that the internal implementation normally calls Array.Copy or CopyTo.
Therefore: It is impossible for AddRange or InsertRange to perform better than a plain Array.Copy.
However: Array.Copy itself may perform better than manually copying elements in a loop.
Summary. AddRange appends a range of values to the end of a List. InsertRange, on the other hand, can insert an array between the elements in a List. These two methods provide a convenient interface to List range manipulations.