How to concatenate two arrays in C#
In this tutorial, we are going to learn about how to concatenate the two arrays in C# with the help of examples.
Concatenation means the joining of two or more arrays into a single array.
Consider, we have the following two arrays:
int[] array1 = { 1, 2, 3 };
int[] array2 = { 4, 5, 6 };
Now, we need to join above two arrays like this:
[1, 2, 3, 4, 5, 6]
Using Enumerable.Concat() method
To concatenate the two arrays into a single array, we can use the Enumerable.Concat() method in C#.
Note: The Enumberable.Concat() is available in System.Linq namespace.
Here is an example:
using System;
using System.Linq;
class ConcatenateArrays {
static void Main() {
int[] array1 = { 1, 2, 3 };
int[] array2 = { 4, 5, 6 };
int[] result = array1.Concat(array2).ToArray();
Console.WriteLine(String.Join(",", result));
}
}
Output:
[1, 2, 3, 4, 5, 6]
Using AddRange() method
Similarly, we can use the AddRange()
method in C# to join two arrays into a single array.
Example:
using System;
using System.Collections.Generic;
class ConcatenateArrays {
static void Main() {
int[] arr1 = {1, 2, 3};
int[] arr2 = {4, 5, 6};
var myList = new List<int>();
myList.AddRange(arr1);
myList.AddRange(arr2);
int[] result = myList.ToArray();
Console.WriteLine(String.Join(",", result));
}
}
In the above code, we have first initialized an empty integer List and then added arr1
and arr2
to the List using the AddRange()
method, at the end we have converted a list to an array using ToArray()
method.