Merge Two Arrays In C#
Code snippet for how to Merge Two Arrays In C# with sample and detail explanation
In C#, merging two arrays allows you to join or combine the elements of two different arrays into one, which can be very useful in various programming tasks. This article will provide a step-by-step explanation on how to merge two arrays in C#.
Code snippet for Merging Arrays in C#
Here is a simple C# code snippet that merges two arrays:
using System;
using System.Linq;
class MergeTwoArrays
{
static void Main(string[] args)
{
int[] array1 = new int[] { 1, 2, 3 };
int[] array2 = new int[] { 4, 5, 6 };
int[] MergedArray = new int[array1.Length + array2.Length];
array1.CopyTo(MergedArray, 0);
array2.CopyTo(MergedArray, array1.Length);
Console.Write("Merged array: ");
foreach (int value in MergedArray)
{
Console.Write(value + " ");
}
}
}
When you run the program, it will print the merged array: 1 2 3 4 5 6
.
Code Explanation for Merging Arrays in C#
Let’s break down the code and understand it step by step:
-
We firstly import required namespaces that will help us to merge arrays.
using System; using System.Linq;
-
Then, we declare and initialize two integer arrays
array1
andarray2
.int[] array1 = new int[] { 1, 2, 3 }; int[] array2 = new int[] { 4, 5, 6 };
-
After this, we create a third array
MergedArray
, which has the combined length ofarray1
andarray2
.int[] MergedArray = new int[array1.Length + array2.Length];
-
We then copy the elements from
array1
intoMergedArray
starting from the 0th index using theCopyTo
method.array1.CopyTo(MergedArray, 0);
-
Also, we copy the elements from
array2
intoMergedArray
starting from the end index ofarray1
.array2.CopyTo(MergedArray, array1.Length);
-
Ultimately, we use a loop to iterate through the array and print out the elements of the
MergedArray
.foreach (int value in MergedArray) { Console.Write(value + " "); }
So, the final output will be the elements of the both arrays merged into one array. This way, you can merge two arrays in C#.