Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matrix to array c#

Tags:

arrays

c#

matrix

Which would be the most efficient way to convert a squared matrix like

  1 2 3 
  4 5 6
  7 8 9 

into

[1 2 3 4 5 6 7 8 9]

in c#

I was doing

int[,] array2D = new int[,] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int[] array1D = new int[9];
int ci=0;

 for (int i = 0; i < 3; i++)
 {
      for (int j = 0; j < 3; j++)
      {
            array1D[ci++] = array2D[i, j]);
      }
 }
like image 633
edgarmtze Avatar asked Jan 18 '23 16:01

edgarmtze


1 Answers

LINQ makes this trivial.

int[,] array2d = ...;
var array1d = array2d.Cast<int>().ToArray();

Otherwise, your way is adequate but could be generalized:

int[,] array2d = ...;
var rows = array2d.GetLength(0);
var cols = array2d.GetLength(1);
var array1d = new int[rows * cols];
var current = 0;
for (int i = 0; i < rows; i++)
{
    for (int j = 0; j < cols; j++)
    {
        array1d[current++] = array2d[i, j];
    }
}

Or even:

int[,] array2d = ...;
var array1d = new int[array2d.GetLength(0) * array2d.GetLength(1)];
var current = 0;
foreach (var value in array2d)
{
    array1d[current++] = value;
}
like image 73
Jeff Mercado Avatar answered Jan 24 '23 23:01

Jeff Mercado