In C#, how can I concatenate two arrays?

Problem

``````int[] x = new int [] { 1, 2, 3};
int[] y = new int [] { 4, 5 };

int[] z = // your answer here...

Debug.Assert(z.SequenceEqual(new int[] { 1, 2, 3, 4, 5 }));
``````

I’m currently using

``````int[] z = x.Concat(y).ToArray();
``````

Is there a better or more efficient way to do this?

Asked by hwiechers

Solution #1

``````var z = new int[x.Length + y.Length];
x.CopyTo(z, 0);
y.CopyTo(z, x.Length);
``````

Answered by Zed

Solution #2

Try this:

``````List<int> list = new List<int>();
list.AddRange(x);
list.AddRange(y);
int[] z = list.ToArray();
``````

Answered by Adriaan Stander

Solution #3

You might make an extension method like this:

``````public static T[] Concat<T>(this T[] x, T[] y)
{
if (x == null) throw new ArgumentNullException("x");
if (y == null) throw new ArgumentNullException("y");
int oldLen = x.Length;
Array.Resize<T>(ref x, x.Length + y.Length);
Array.Copy(y, 0, x, oldLen, y.Length);
return x;
}
``````

Then:

``````int[] x = {1,2,3}, y = {4,5};
int[] z = x.Concat(y); // {1,2,3,4,5}
``````

Answered by Marc Gravell

Solution #4

I came up with a more general-purpose method that allows you to concatenate any number of one-dimensional arrays of the same type. (I was concatenating three or more items at a time.)

My function:

``````    public static T[] ConcatArrays<T>(params T[][] list)
{
var result = new T[list.Sum(a => a.Length)];
int offset = 0;
for (int x = 0; x < list.Length; x++)
{
list[x].CopyTo(result, offset);
offset += list[x].Length;
}
return result;
}
``````

And usage:

``````        int[] a = new int[] { 1, 2, 3 };
int[] b = new int[] { 4, 5, 6 };
int[] c = new int[] { 7, 8 };
var y = ConcatArrays(a, b, c); //Results in int[] {1,2,3,4,5,6,7,8}
``````

Answered by deepee1

Solution #5

This is it:

``````using System.Linq;

int[] array1 = { 1, 3, 5 };
int[] array2 = { 0, 2, 4 };

// Concatenate array1 and array2.
var result1 = array1.Concat(array2);
``````

Answered by Roland

Post is based on https://stackoverflow.com/questions/1547252/how-do-i-concatenate-two-arrays-in-c