OneBite.Dev - Coding blog in a bite size

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:

  1. We firstly import required namespaces that will help us to merge arrays.

    using System; 
    using System.Linq;
  2. Then, we declare and initialize two integer arrays array1 and array2.

    int[] array1 = new int[] { 1, 2, 3 };
    int[] array2 = new int[] { 4, 5, 6 };
  3. After this, we create a third array MergedArray, which has the combined length of array1 and array2.

    int[] MergedArray = new int[array1.Length + array2.Length];
  4. We then copy the elements from array1 into MergedArray starting from the 0th index using the CopyTo method.

    array1.CopyTo(MergedArray, 0);
  5. Also, we copy the elements from array2 into MergedArray starting from the end index of array1.

    array2.CopyTo(MergedArray, array1.Length);
  6. 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#.

c-sharp