Convert multidimensional array to jagged array in C#

前端 未结 3 1909
花落未央
花落未央 2020-12-17 18:10

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

3条回答
  •  北海茫月
    2020-12-17 18:43

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

提交回复
热议问题