In C#, the data structures that allow us to store and manipulate the group of objects are known as collections. Collections play a vital role in the functionality of a wide array of usage.
Like all the data structures, you will find yourself needing to perform various operations on them. For example, you might need to add new elements, remove the existing elements, sort the elements, etc.
One of the most useful method for manipulating the collections in C# is the AddRange() method. As you can guess, this method is part of the System.Collections.Generic namespace and offers a way to add the elements to an end of a collection. This removes the need to manually iterate over the structure which can have a heavy performance penalty for large values.
In this tutorial, we will take you into the fundamental functionality of this function and discuss its syntax, supported parameters, and the various operations that you can perform with it.
C# AddRange Method
The following snippet demonstrates the basic syntax of the AddRange() method:
The method accepts the collection whose elements should be added to the end of the List<T>. The provided collection cannot be null and must contain the elements of similar type to the list.
Examples:
Let us explore some practical examples on how we can use this method to perform the various operations on C# collections.
Example 1: Add Elements to the List
The most basic example is adding multiple elements into a list using the AddRange() method. Take a look at the following example:
In this example, we declare two list of integers. We then use the AddRange() method to add all elements of the second list to the first list. Finally, we iterate over the new list and return the resulting elements.
You might notice that the code prints all the elements as they appear in both arrays.
Example 2: Add an Array to the List
We can also use the AddRange() method to add an array of elements to an existing list. An example is as follows:
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<string> dbs = new List<string> { "MySQL", "PostgreSQL" };
string[] nosql = { "Redis", "Elastic", "Cassanrdra" };
dbs.AddRange(nosql);
foreach (var db in dbs)
{
Console.WriteLine(db);
}
}
}
In this example, we use the AddRange() method to append an array of elements into an existing list.
Conclusion
In this tutorial, we explored the fundamentals of working with the AddRange() method to add elements to an existing collection. This method is a much more efficient alternative to manually add each element via iteration.