Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How do I concatenate two arrays in C#?

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 }));


Right now I use

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


Is there an easier or more efficient method?
by

2 Answers

vishaljlf39
You should try this
var z = new int[x.Length + y.Length];
x.CopyTo(z, 0);
y.CopyTo(z, x.Length);
pankajshivnani123
You could write an extension method:

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}

Login / Signup to Answer the Question.