How to resize multidimensional (2D) array in C#?

Viewed 65549

I tried the following but it just returns a screwed up array.

    T[,] ResizeArray<T>(T[,] original, int rows, int cols)
    {
        var newArray = new T[rows,cols];
        Array.Copy(original, newArray, original.Length);
        return newArray;
    }
7 Answers

This builds on Manuel's answer to also allow to apply an offset to the copied data (e.g. to copy the source array to the center of the target array, instead of to [0, 0]):

public static T[,] ResizeArray<T>(T[,] original, int newWidth, int newHeight, int offsetX = 0, int offsetY = 0)
{
    T[,] newArray = new T[newWidth, newHeight];
    int width = original.GetLength(0);
    int height = original.GetLength(1);
    for (int x = 0; x < width; x++) {
        Array.Copy(original, x * height, newArray, (x + offsetX) * newHeight + offsetY, height);
    }

    return newArray;
}

I really like Stephen Tierney's answer building upon the work of others. As Stephen notes the x/y is up to interpretation.

I have refactored it slightly to use m*n sizes & ij coordinate indexing that is probably the most common notation for matrices (wikipedia for reference https://en.wikipedia.org/wiki/Matrix_(mathematics)).

In this notation,

  • 'm' is the number of rows
  • 'n' is the number of columns
  • 'i' is the first coordinate, aka row index (increases as you go down)
public static T[,] Resize2D<T>(this T[,] original, int m, int n)
{

    T[,] newArray = new T[m, n];
    int mMin = Math.Min(original.GetLength(0), newArray.GetLength(0));
    int nMin = Math.Min(original.GetLength(1), newArray.GetLength(1));

    for (int i = 0; i < mMin; i++)
        Array.Copy(original, i * original.GetLength(1), newArray, i * newArray.GetLength(1), nMin);

    return newArray;
}
Related