How to Resize Multidimensional (2D) Array in C#

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

Thank you Thomas, your explanation was very helpful but your implemented solution is too slow. I modified it to put Array.Copy to good use.

    void ResizeArray<T>(ref T[,] original, int newCoNum, int newRoNum)
{
var newArray = new T[newCoNum,newRoNum];
int columnCount = original.GetLength(1);
int columnCount2 = newRoNum;
int columns = original.GetUpperBound(0);
for (int co = 0; co <= columns; co++)
Array.Copy(original, co * columnCount, newArray, co * columnCount2, columnCount);
original = newArray;
}

Here I'm assuming that there are more rows than columns so I structured the array as [columns, rows]. That way I use Array.Copy on an entire column in one shot (much faster than one cell a time).

It only works to increment the size of the array but it can probably be tweaked to reduce the size too.

Resizing and initializing 2D array C#

Instead of a 2D array you might want to use a jagged one. Briefly, a 2D array is always an N x M matrix, which you cannot resize, whereas a jagged array is an array of arrays, where you can separately initialize every inner element by a different size (see the differences in details here)

int maxBound = 100;
Random rnd = new Random();
int numLoops = rnd.Next(1000, 1200);

string[][] jagged = new string[numLoops][];

for (int i = 0; i < numLoops; i++)
{
int currLen = rnd.Next(maxBound);
jagged[i] = new string[currLen];

for (int j = 0; j < currLen; j++)
jagged[i][j] = "*"; // do some initialization
}

Extend 2D array size?

What you want is a List of Lists.

List<List<int>> data = new List<List<int>>();

for(int i = 0; i < rowsToAdd; i++)
{
List<int> newRow = new List<int>();
for(int j = 0; j < columnsToAdd; j++)
{
newRow.Add(j);
}
data.Add(newRow);
}

Then to add a new row:

List<int> nextRow = new List<int>(){0,1,2,3};
data.Add(nextRow);

Resize matrix in c#

You have to specify what T is. Assuming myMatrix contains elements of type double, you need

ResizeArray<double>(myMatrix, 3, 3)


Related Topics



Leave a reply



Submit