Merge two sorted arrays into a list using C#


To merge two sorted arrays into a list, firstly set two sorted arrays −

int[] array1 = { 1, 2 };
int[] array2 = { 3, 4 };

Add it to a list and merge −

var list = new List<int>();
for (int i = 0; i < array1.Length; i++) {
   list.Add(array1[i]);
      list.Add(array2[i]);
}

Now, use the ToArray() method to convert back into an array as shown below −

Example

 Live Demo

using System;
using System.Collections.Generic;

public class Program {
   public static void Main() {
      int[] array1 = { 56, 70, 77};
      int[] array2 = { 80, 99, 180};
      var list = new List<int>();

      for (int i = 0; i < array1.Length; i++) {
         list.Add(array1[i]);
         list.Add(array2[i]);
      }
      int[] array3 = list.ToArray();

      foreach(int res in array3) {
         Console.WriteLine(res);
      }
   }
}

Output

56
80
70
99
77
180

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 22-Jun-2020

166 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements