C#将1D数组转换为2D

Dr.*_*YSG 4 c# linq

我发现自己通过执行以下操作将1D字节和单个数组转换为2D.我怀疑它可能和其他方法一样快,但也许有一个更简洁的范例?(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;
    }
Run Code Online (Sandbox Code Playgroud)

rya*_*uyu 9

这对于使方法中的代码更清晰没有帮助,但我注意到你有两个基本相同的方法,它们的类型不同.我建议使用泛型.

这样您就可以只定义一次方法了.使用where关键字,您甚至可以限制允许方法处理的类型类型.

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;
}
Run Code Online (Sandbox Code Playgroud)

你可以像这样调用这个方法

int[] a;  //or any other array.
var twoDArray = Make2DArray(a, height, width);
Run Code Online (Sandbox Code Playgroud)


Sla*_*lai 6

Buffer.BlockCopy(input, 0, output, 0, input.Length);更快,但最快的是根本不复制数组。

如果您确实不需要单独的 2D 数组,则可以像通过函数、属性或自定义类型访问 2D 数组一样访问 1D 数组。例如:

class D2<T> {
    T[] input;
    int lenght0;
    public d2(T[] input, int lenght0) {
        this.input = input;
        this.lenght0 = lenght0;
    }
    public T this[int index0, int index1] {
        get { return input[index0 * this.lenght0 + index1]; }
        set { input[index0 * this.lenght0 + index1] = value; }
    }
}

...

byte[] input = { 1, 2, 3, 4 };
var output = new D2<byte>(input, 2);
output[1, 1] = 0;  // now input is { 1, 2, 3, 0 };
Run Code Online (Sandbox Code Playgroud)

此外,在 .NET 中,访问多维数组比访问交错数组要慢一些