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

通过执行以下操作,我发现自己将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; } 

这对于使方法中的代码更清晰无效,但我注意到你有两个基本相同的方法,它们的类型不同。 我建议使用generics 。

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

 private static T[,] Make2DArray(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; } 

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

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

通用function:

 private static b[,] to2D(a source, valueAt: Func, int height, int width) { var result = new b[height, width]; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { result[i, j] = valueAt(source, i * width + j); } } return result; } var bytes = to2D([], (bytes, at) => bytes[at], 10, 20); 

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

如果您不需要单独的2Darrays,则只需通过函数,属性或自定义类型访问2Darrays即一维数组。 例如:

 class D2 { 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(input, 2); output[1, 1] = 0; // now input is { 1, 2, 3, 0 }; 

此外,在.NET中,对多维数组的访问比访问锯齿状数组要慢一些