简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM