C# How To Merge Two Arrays
Merge Two Arrays
Use the Concat() method from the System.Linq namespace to join two arrays, and ToArray() to turn the result into a new array:
Example
int[] first = {1, 2, 3};
int[] second = {4, 5, 6};
int[] merged = first.Concat(second).ToArray();
foreach (int num in merged)
{
Console.WriteLine(num);
}
You can also create a new array that is large enough for both, and copy the elements into it with CopyTo():
Example
int[] first = {1, 2, 3};
int[] second = {4, 5, 6};
int[] merged = new int[first.Length + second.Length];
first.CopyTo(merged, 0);
second.CopyTo(merged, first.Length);
foreach (int num in merged)
{
Console.WriteLine(num);
}
Explanation:Concat() puts the elements of second after the elements of first.
An array has a fixed size, so the second example creates merged with room for 6 elements. CopyTo() copies all the elements into it, starting at the given position (0 and 3).