OneBite.Dev - Coding blog in a bite size

Merge Two Arrays Together In C#

Code snippet for how to Merge Two Arrays Together In C# with sample and detail explanation

Merging two arrays together in C# is a common operation that programmers might need to perform. This task can be done easily using some pre-existing methods and a few lines of code.

Code Snippet: Merging Two Arrays in C#

Below is a concise code snippet demonstrating how to merge two arrays in C#:

int[] Array1 = { 1, 2, 3 };
int[] Array2 = { 4, 5, 6 };
int[] MergedArray = new int[Array1.Length + Array2.Length];
Array1.CopyTo(MergedArray, 0);
Array2.CopyTo(MergedArray, Array1.Length);

Code Explanation: Merging Two Arrays in C#

In this code, we start by initializing two integer arrays, Array1 and Array2, with some values. Next, we define a new array ‘MergedArray’ that will be used to store the merged array. The length of ‘MergedArray’ is defined as the sum of lengths of Array1 and Array2 to ensure it has enough storage to hold all elements from both arrays.

int[] Array1 = { 1, 2, 3 };
int[] Array2 = { 4, 5, 6 };
int[] MergedArray = new int[Array1.Length + Array2.Length];

The ‘CopyTo’ method is then used to copy each of the arrays into ‘MergedArray’. For ‘Array1’, the copy starts at the beginning of ‘MergedArray’, which is indexed at position 0.

Array1.CopyTo(MergedArray, 0);

For ‘Array2’, the copy starts where ‘Array1’ ended, which is at the index position which is equivalent to the length of ‘Array1’.

Array2.CopyTo(MergedArray, Array1.Length);

At the end of this operation, ‘MergedArray’ will contain all elements from both ‘Array1’ and ‘Array2’, effectively merging the two arrays. The order of elements in the merged array will adhere to the order of elements in the input arrays and the order in which the arrays were copied into the merged array.

c-sharp