Home > Back-end >  Converting a 2d array to a 1d List, then back to a 2d array
Converting a 2d array to a 1d List, then back to a 2d array

Time:12-11

In order to serialize a 2d array I am first flattening it like so:

InfoCell[,] cells = new InfoCell[size, size];
List<InfoCell> flattenedCells= new List<InfoCell>();

foreach(InfoCell infoCell in cells )
{
    flattenedCells.Add(infoCell);
}

Knowing the size of the 2d array, how can I convert this 1d List back into a 2d array?

CodePudding user response:

You can try something like this:

var array = new string[rowsSize, columnSize];
var list = new List<string>();
for (var i = 0; i < rowsSize; i  )
{
   for (var j = 0; j < columnSize; j  )
   {
      list.Add(array[i,j]);
   }   
}

var newArray = new string[rowsSize, columnSize];
for (var i = 0; i < rowsSize; i  )
{
   for (var j = 0; j < columnSize; j  )
   {
       var index = i * columnSize   j;
       newArray[i, j] = list[index];
   }   
}
        
  • Related