C# List AddRange Use

AddRange adds an entire collection of elements. It can replace tedious foreach loops that repeatedly call Add on List. You can pass any IEnumerable collection to AddRange, not just an array or another List.

Illustration

Example

We look at the AddRange instance method from the base class library in the C# language on List. This example show you can add a range at the end of the List using the AddRange method. The term 'range' simply means an IEnumerable collection, which includes List, arrays, and others.

This C# example program uses the AddRange method on the List type.

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
Note

Description. Above, 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. The end result of the above program is that it displays seven integers, which are the union of the List itself and the array we added with AddRange.

Implementation

.NET Framework information

I wanted to know how AddRange and its friend InsertRange actually do in the runtime. I found out that AddRange is a wrapper method on top of InsertRange. For more information on the implementation of InsertRange, there is a useful article on that method on this site.

InsertRange List Method, Insert Array Into List

Performance

Performance optimization

First, we know that AddRange and InsertRange are the same method internally. Second, we know from the compiled code above that the internal implementation calls Array.Copy or CopyTo normally. Therefore, it is impossible for AddRange or InsertRange to perform better than a plain Array.Copy. However, Array.Copy itself may well perform better than manually copying elements.

Array.Copy Method Usage

Summary

The C# programming language

We saw how to use AddRange to append a range of values to the very 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.

Collections
.NET