Combine two arrays in C#

CsharpProgrammingServer Side Programming

Firstly, declare and initialize two arrays −

int[] arr1 = { 37, 45, 65 };
int[] arr2 = { 70, 89, 118 };

Now create a new list −

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

Use the AddRange() method the arrays into the newly created list.

myList.AddRange(arr1);
myList.AddRange(arr2);

Now convert the list into array as shown below −

Example

 Live Demo

using System;
using System.Collections.Generic;
class Demo {
   static void Main() {
      int[] arr1 = { 37, 45, 65 };
      int[] arr2 = { 70, 89, 118 };
      // 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("Combined array elements..");
      foreach (int res in arr3) {
         Console.WriteLine(res);
      }
   }
}

Output

Array 1...
37
45
65
Array 2...
70
89
118
Combined array elements..
37
45
65
70
89
118
raja
Published on 04-Sep-2018 14:31:19
Advertisements