Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# convert 1D array to 2D

Tags:

c#

linq

I find myself converting 1D byte and single arrays to 2D by doing the following. I suspect it is probably as fast as other methods, but perhaps there is a cleaner simpler paradigm? (Linq?)

    private static byte[,] byte2D(byte[] input, int height, int width)
    {
        byte[,] output = new byte[height, width];
        for (int i = 0; i < height; i++)
        {
            for (int j = 0; j < width; j++)
            {
                output[i, j] = input[i * width + j];
            }
        }
        return output;
    }

    private static Single[,] single2D(byte[] input, int height, int width)
    {
        Single[,] output = new Single[height, width];
        for (int i = 0; i < height; i++)
        {
            for (int j = 0; j < width; j++)
            {
                output[i, j] = (Single)input[i * width + j];
            }
        }
        return output;
    }
like image 486
Dr.YSG Avatar asked Jan 23 '15 15:01

Dr.YSG


1 Answers

This doesn't help with making the code inside the methods cleaner, but I noticed that you have 2 basically identical methods that differ only in their types. I suggest using generics.

This would let you define your method only once. Using the where keyword, you can even limit the kind of types you allow your method to work on.

private static T[,] Make2DArray<T>(T[] input, int height, int width)
{
    T[,] output = new T[height, width];
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            output[i, j] = input[i * width + j];
        }
    }
    return output;
}

You would call this method like this

int[] a;  //or any other array.
var twoDArray = Make2DArray(a, height, width);
like image 187
ryanyuyu Avatar answered Oct 22 '22 22:10

ryanyuyu