C# convert 1D array to 2D
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);
Buffer.BlockCopy(input, 0, output, 0, input.Length);
is faster, but fastest is to not copy the array at all.
If you don't really need a separate 2D array, you can just access your 1D array like a 2D array trough a function, property, or custom type. For example:
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 };
Also, in .NET access to multidimensional arrays is a bit slower than access to jagged arrays