How to Concatenate Two Arrays in C#

How do I concatenate two arrays in C#?

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

Merging two arrays in .NET

If you can manipulate one of the arrays, you can resize it before performing the copy:

T[] array1 = getOneArray();
T[] array2 = getAnotherArray();
int array1OriginalLength = array1.Length;
Array.Resize<T>(ref array1, array1OriginalLength + array2.Length);
Array.Copy(array2, 0, array1, array1OriginalLength, array2.Length);

Otherwise, you can make a new array

T[] array1 = getOneArray();
T[] array2 = getAnotherArray();
T[] newArray = new T[array1.Length + array2.Length];
Array.Copy(array1, newArray, array1.Length);
Array.Copy(array2, 0, newArray, array1.Length, array2.Length);

More on available Array methods on MSDN.

Most efficient way to append arrays in C#?

You can't append to an actual array - the size of an array is fixed at creation time. Instead, use a List<T> which can grow as it needs to.

Alternatively, keep a list of arrays, and concatenate them all only when you've grabbed everything.

See Eric Lippert's blog post on arrays for more detail and insight than I could realistically provide :)

Combining two int's arrays into one array by order not working

All we need is for loop:

static void Merge(int[] left, int[] right) 
for (int indexLeft = 0, indexRight = 0;
indexLeft < left.Length || indexRight < right.Length;)
if (indexRight >= right.Length ||
(indexLeft < left.Length && left[indexLeft] <= right[indexRight]))
Console.WriteLine(left[indexLeft++]);
else
Console.WriteLine(right[indexRight++]);
}

we move by both left and right arrays (indexLeft, indexRight) and we print item from left array if and only if

  1. We exhausted right array: indexRight >= right.Length.
  2. If we have items in both left and right arrays and left[indexLeft] <= right[indexRight]

otherwise we print right array item.

Edit: If you want to return merged array (result):

static int[] Merge(int[] left, int[] right) {
int[] result = new int[left.Length + right.Length];
int index = 0;

for (int indexLeft = 0, indexRight = 0;
indexLeft < left.Length || indexRight < right.Length;)
if (indexRight >= right.Length ||
(indexLeft < left.Length && left[indexLeft] <= right[indexRight]))
result[index++] = left[indexLeft++];
else
result[index++] = right[indexRight++];

return result;
}

Array concatenation in C#

You could use CopyTo:

double[] d1 = new double[5];
double[] d2 = new double[3];
double[] dTotal = new double[d1.Length + d2.Length];

d1.CopyTo(dTotal, 0);
d2.CopyTo(dTotal, d1.Length);

Combine elements of two arrays in pairs

You can do this with a one liner using the Enumerable.Zip extension method found in System.Linq and String.Join:

tw.WriteLine(string.Join(Environment.NewLine, comet1.Zip(paramet1, (f, s) => $"{f}\\{s}")));

Read the documentation of both methods in the provided links to understand exactly what they do.



Related Topics



Leave a reply



Submit