Merge two arrays using C# AddRange() method


Firstly, set two arrays −

int[] arr1 = { 15, 20, 27, 56 };
int[] arr2 = { 62, 69, 76, 92 };

Now create a new list and use AddRange() method to merge −

var myList = new List<int>();
myList.AddRange(arr1);
myList.AddRange(arr2);

After that, convert the merged collection to an array −

int[] arr3 = myList.ToArray()

Let us see the complete code

Example

 Live Demo

using System;
using System.Collections.Generic;
class Demo {
   static void Main() {
      int[] arr1 = { 15, 20, 27, 56 };
      int[] arr2 = { 62, 69, 76, 92 };
      // displaying array1
      Console.WriteLine("Array 1...");
      foreach(int ele in arr1) {
         Console.WriteLine(ele);
      }
      // displaying array2
      Console.WriteLine("Array 2...");
      foreach(int ele in arr2) {
         Console.WriteLine(ele);
      }
      var myList = new List<int>();
      myList.AddRange(arr1);
      myList.AddRange(arr2);
      int[] arr3 = myList.ToArray();
      Console.WriteLine("Merged array..");
      foreach (int res in arr3) {
         Console.WriteLine(res);
      }
   }
}

Output

Array 1...
15
20
27
56
Array 2...
62
69
76
92
Merged array..
15
20
27
56
62
69
76
92

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 22-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements