Title: Convert between ragged arrays and twodimensional arrays
Ragged arrays are arrays that hold other arrays, as opposed to twodimensional arrays. They are called "ragged arrays" because they work like twodimensional arrays (or higherdimensional arrays) where each row in the array can hold a different number of elements.
Converting between ragged arrays and twodimensional arrays isn't too hard, it just requires some bookkeeping. You can also use generic parameters to make a method to convert between ragged arrays and twodimensional arrays holding any type of objects.
The following extension method converts from a twodimensional array to a ragged array.
// Convert T[,] to T[][].
public static T[][] ToRagged<T>(this T[,] values)
{
// Get the number of rows and columns.
int num_rows = values.GetUpperBound(0) + 1;
int num_cols = values.GetUpperBound(1) + 1;
// Make the ragged array.
T[][] result = new T[num_rows][];
// Copy values into the ragged array.
for (int r = 0; r < num_rows; r++)
{
result[r] = new T[num_cols];
for (int c = 0; c < num_cols; c++)
result[r][c] = values[r, c];
}
return result;
}
The method first gets the twodimensional array's dimensions. It then creates a onedimensional array to hold the ragged array's rows.
The code then loops through the twodimensional array's rows. For each row, the method creates a onedimensional array to hold the row's values and then copies the values into the row.
The following extension method converts a ragged array into a twodimensional array.
// Convert T[][] to T[,].
public static T[,] To2DArray<T>(this T[][] values)
{
// Get the number of rows.
int num_rows = values.GetUpperBound(0) + 1;
// Get the maximum number of columns in any row.
int num_cols = 0;
for (int r = 0; r < num_rows; r++)
if (num_cols < values[r].Length)
num_cols = values[r].Length;
// Make the twodimensional array.
T[,] result = new T[num_rows, num_cols];
// Copy values into the ragged array.
for (int r = 0; r < num_rows; r++)
{
for (int c = 0; c < values[r].Length; c++)
result[r, c] = values[r][c];
}
return result;
}
This method gets the number of rows in the ragged array. It then loops through its rows to see how long its longest row is.
The code then allocates a twodimensional array with the correct number of rows and columns. It then loops through the ragged array's values adding them to the twodimensional array.
Note that any entries in the twodimensional array that do not correspond to entries in the ragged array are left uninitialized. For example, suppose the longest row in the ragged array has 25 entries but the first row has only 10 entries. In that case, the last 15 entries in the first row of the result array will hold only 10 values and the last 15 values will be uninitialized and will holdd the default value for their data type.
Download the example to experiment with it and to see additional details.
