Merge two sorted arrays into a list using C#

CsharpProgrammingServer Side Programming

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
raja
Published on 31-Aug-2018 12:20:13
Advertisements