C# AddRange

AddRange adds an entire collection of elements. 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.

Array data

Example

Note

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.

IEnumerableInt Array
Program that uses AddRange: C#

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
Array type

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.

Console.WriteLine

Internals

Framework: NET

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.

InsertRange

Performance

Performance optimization

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.

Array.Copy Method

Summary

The C# programming language

We saw how to use AddRange to append 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.

But:They can result in extra copying and CPU usage in a poorly-developed algorithm.


C#: Collections: List