ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

Convert a Rectangular to a Jagged Array

Converts a T[,] (rectangular array) to a T[][] (jagged array).

Source

public static T[][] ToJaggedArray<T>(this T[,] multiArray)
{
    int firstElement = multiArray.GetLength(0);
    int secondElement = multiArray.GetLength(1);

    T[][] jaggedArray = new T[firstElement][];

    for (int c = 0; c < firstElement; c++)
    {
        jaggedArray[c] = new T[secondElement];
        for (int r = 0; r < secondElement; r++)
        {
            jaggedArray[c][r] = multiArray[c, r];
        }
    }
    return jaggedArray;
}

Example

string[,] rectangular_array = new string[3,3];
string[][] jagged_array = rectangular_array.ToJaggedArray();

Author: Siddhartha Gandhi

Submitted on: 1 dec. 2016

Language: C#

Type: Object

Views: 4074