Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I concatenate two arrays in C#?

Tags:

arrays

c#

.net

linq

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?


Be careful with the Concat method. The post Array Concatenation in C# explains that:

var z = x.Concat(y).ToArray();

Will be inefficient for large arrays. That means the Concat method is only for meduim-sized arrays (up to 10000 elements).

like image 353
hwiechers Avatar asked Oct 10 '09 06:10

hwiechers


People also ask

Can you concatenate arrays in C?

To concate two arrays, we need at least three array variables. We shall take two arrays and then based on some constraint, will copy their content into one single array. Here in this example, we shall take two arrays one will hold even values and another will hold odd values and we shall concate to get one array.

How do I combine two arrays?

To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.

Can you concatenate an array?

concat() The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

What is merging of array in C?

CServer Side ProgrammingProgramming. Take two arrays as input and try to merge or concatenate two arrays and store the result in third array. The logic to merge two arrays is given below − J=0,k=0 for(i=0;i<o;i++) {// merging two arrays if(a[j]<=b[k]){ c[i]=a[j]; j++; } else { c[i]=b[k]; k++; } }


3 Answers

var z = new int[x.Length + y.Length];
x.CopyTo(z, 0);
y.CopyTo(z, x.Length);
like image 169
Zed Avatar answered Oct 19 '22 20:10

Zed


Try this:

List<int> list = new List<int>();
list.AddRange(x);
list.AddRange(y);
int[] z = list.ToArray();
like image 107
Adriaan Stander Avatar answered Oct 19 '22 19:10

Adriaan Stander


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}
like image 61
Marc Gravell Avatar answered Oct 19 '22 19:10

Marc Gravell