OneBite.Dev - Coding blog in a bite size

Merge Multiple Array In C#

Code snippet for how to Merge Multiple Array In C# with sample and detail explanation

The merging of multiple arrays in C# is a common task in programming, crucial to data handling and manipulation. In this article, we’ll navigate through a practical example of this process by understanding the approach and the code behind it.

Code snippet for Merging Arrays

using System; 
using System.Linq; 

class GFG { 

    // Main Method 
    static public void Main() 
    {
 
        // Creating and initializing first array
        int[] array1 = {1, 2, 3}; 

        // Creating and initializing second array 
        int[] array2 = {4, 5, 6}; 

        // Creating and initializing third array 
        int[] array3 = {7, 8, 9}; 

        // Using Concat() method to merge the arrays
        var array = array1.Concat(array2).Concat(array3);
 
        // Displaying merged array
        foreach (int value in array) { 
            Console.Write(value + " "); 
        } 
    } 
}

Code Explanation for Merging Arrays

Start by importing the necessary libraries. In this case, import System and System.Linq for array manipulation.

using System; 
using System.Linq; 

Next, declare a class where all operations will be performed.

class GFG { 

Inside the main function where the program starts, you can initialize three arrays.

    int[] array1 = {1, 2, 3}; 
    int[] array2 = {4, 5, 6}; 
    int[] array3 = {7, 8, 9}; 

Now, using the Concat() function from the System.Linq namespace, merge the arrays. This function concatenates two sequences, and since it only takes two parameters, you need to call it multiple times to join more than two arrays.

var array = array1.Concat(array2).Concat(array3);

Finally, use a foreach loop to iterate and display the elements of the merged array.

foreach (int value in array) { 
    Console.Write(value + " "); 
} 

And there you go! That’s the way to seamlessly merge multiple arrays in C#. The more you practice, the more familiar and comfortable you will become with this kind of operation – happy coding!

c-sharp