Efficient conversion of an array into a two-dimensional one using LINQ
I want to do 开发者_开发技巧the below in a performant way in C#, preferably using LINQ.
Array[Length]
to Array[Length/Row][Row]
where Row
and Length
are variables.
You can use Buffer.BlockCopy to efficiently convert between n-dimensional arrays of blittable types:
int[] a = new int[] { 1, 2, 3, 4, 5, 6 };
int rows = 2;
int columns = a.Length / rows;
int[,] b = new int[columns, rows];
Buffer.BlockCopy(a, 0, b, 0, sizeof(int) * a.Length);
// b[0, 0] == 1
// b[0, 1] == 2
// b[1, 0] == 3
// b[1, 1] == 4
// b[2, 0] == 5
// b[2, 1] == 6
This takes advantage of the fact that multi-dimensional (not jagged!) arrays are laid out continuously in memory by the CLR.
For non-blittable types, simply use some good ol' for
loops.
That's not a two dimensional array, that's a jagged array. I assume that you mean Array[Length/Row,Row]
.
There isn't anything in LINQ that does exactly that, so you will have a bit of overhead if you want to use it. The most performant way is straight forward code:
public T[,] MakeRows<T>(T[] values, int rowSize) {
T[,] result = new T[values.Length / rowSize, rowSize];
int row = 0, col = 0;
foreach (T value in values) {
resul[row, col] = value;
if (++col == rowsize) {
col = 0;
row++;
}
}
return result;
}
Note: The method assumes that the items are evenly divisable into rows.
精彩评论