Convert multidimensional array to jagged array in C#

c#, jagged-arrays, multidimensional-array

Solution

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;
    }
}

Problem

I have a C# WCF webservice which is called by two VB 6 project. The target VB project is sending to the client VB project a multidimensional array. I want to convert the multidimensional array to a jagged array but i have no luck. How can i find the number of olements in my object[,] to be able to initialize the jagged array ? I want to follow the answer from this question but i don't have a `GetLength` method on my object. I tried : ``` int firstElement = astrManTfrLetters.GetLength(0); int secondElement = astrManTfrLetters.GetLength(1); ``` And i stuck here.

Original source

Related problems