1

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.

2
  • Could you give an example of how the data you are trying to convert looks? Commented Sep 20, 2010 at 22:18
  • LINQ-to-Objects deals with IEnumerable's, not directly with arrays. Two-dimensional arrays are not really supported at all. Commented Sep 20, 2010 at 22:27

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.