Convert multidimensional array to jagged array in C#
Usually the solutions presented assume 0-based indices but that's not always the case, mainly if on the client you are dealing with object[,]
's for Microsoft Excel.
Here is a solution for any indices:
internal static class ExtensionMethods
{
internal static T[][] ToJaggedArray<T>(this T[,] twoDimensionalArray)
{
int rowsFirstIndex = twoDimensionalArray.GetLowerBound(0);
int rowsLastIndex = twoDimensionalArray.GetUpperBound(0);
int numberOfRows = rowsLastIndex + 1;
int columnsFirstIndex = twoDimensionalArray.GetLowerBound(1);
int columnsLastIndex = twoDimensionalArray.GetUpperBound(1);
int numberOfColumns = columnsLastIndex + 1;
T[][] jaggedArray = new T[numberOfRows][];
for (int i = rowsFirstIndex; i <= rowsLastIndex; i++)
{
jaggedArray[i] = new T[numberOfColumns];
for (int j = columnsFirstIndex; j <= columnsLastIndex; j++)
{
jaggedArray[i][j] = twoDimensionalArray[i, j];
}
}
return jaggedArray;
}
}
By default, the C# produces the 0-based array. I have fine-tuned Pedro's solution as below:
internal static class ExtensionMethods
{
internal static T[][] ToJaggedArray<T>(this T[,] twoDimensionalArray)
{
int rowsFirstIndex = twoDimensionalArray.GetLowerBound(0);
int rowsLastIndex = twoDimensionalArray.GetUpperBound(0);
int numberOfRows = rowsLastIndex - rowsFirstIndex + 1;
int columnsFirstIndex = twoDimensionalArray.GetLowerBound(1);
int columnsLastIndex = twoDimensionalArray.GetUpperBound(1);
int numberOfColumns = columnsLastIndex - columnsFirstIndex + 1;
T[][] jaggedArray = new T[numberOfRows][];
for (int i = 0; i < numberOfRows; i++)
{
jaggedArray[i] = new T[numberOfColumns];
for (int j = 0; j < numberOfColumns; j++)
{
jaggedArray[i][j] = twoDimensionalArray[i + rowsFirstIndex, j + columnsFirstIndex];
}
}
return jaggedArray;
}
}
This worked for me and did not require any looping. It took a object[85000,26] and converted it to object[85000][26] in a little over a second.
object[,] obj2D = ...
// Take my 2D array and cast it as a 1D array
object[] obj1D = ((object[,]) obj2D).Cast<object>().ToArray();
// using linq, chunk the 1D array back into a jagged array
Int32 j = 0;
object[][] jagged = obj1D.GroupBy(x => j++ / obj2D.GetLength(1)).Select(y => y.ToArray()).ToArray();