convert integer 1D array to int 2D array.  
Author Message
Tammt





PostPosted: Visual C# General, convert integer 1D array to int 2D array. Top

How can I convert int 1D array to int 2D array

Thanks,

Tammy



Visual C#3  
 
 
cverdon





PostPosted: Visual C# General, convert integer 1D array to int 2D array. Top

Hi,

What do you mean exactly, there are more than one possibility. Can you give an example...

Charles


 
 
Paul Louth





PostPosted: Visual C# General, convert integer 1D array to int 2D array. Top

This should work, you pick the desired size of the 2D array, then it fits as much of the 1D array in as possible.

public static int[,] Covert1DArrayTo2DArray(int[] src, int desiredWidth, int desiredHeight)
{
int[,] dest = new int[desiredWidth, desiredHeight];

int count = src.Length;
if (desiredWidth * desiredHeight < count)
{
count = desiredWidth * desiredHeight;
}

int index=0;
for (int y = 0; y < desiredHeight; y++)
{
for (int x = 0; x < desiredWidth; x++)
{
dest[x, y] = src[index++];
if (index == count)
{
return dest;
}
}
}
return dest;
}


 
 
Tammt





PostPosted: Visual C# General, convert integer 1D array to int 2D array. Top

Thanks Paul. It works great!

Tammy


 
 
Paul Louth





PostPosted: Visual C# General, convert integer 1D array to int 2D array. Top

Cool :)