How to convert a two-dimensional array to one-dimensional array in C#

1 Answer

0 votes
using System;

class Program
{
    static void Main() {
        int[,] array2d = { { 4, 6 }, 
                           { 5, 7 },
                           { 0, 1 }, 
                           { 9, 12 },
                           { 8, 16 }, 
                           { 69, 98 } };
                             
        int index = 0;
        int rows = array2d.GetLength(0);
        int cols = array2d.GetLength(1);
        int[] arr = new int[rows * cols];
            
        for (int i = 0; i < cols; i++) {
            for (int j = 0; j < rows ; j++) {
                arr[index] = array2d[j, i];
                index++;
            }
        }
        foreach (int n in arr) {
            Console.Write(n + " ");
        }
    }
}





/*
run:
  
4 5 0 9 8 69 6 7 1 12 16 98 

*/

 



answered Sep 5, 2021 by avibootz
...