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).
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.
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.
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.
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++; } }
var z = new int[x.Length + y.Length];
x.CopyTo(z, 0);
y.CopyTo(z, x.Length);
Try this:
List<int> list = new List<int>();
list.AddRange(x);
list.AddRange(y);
int[] z = list.ToArray();
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With