Converting jagged array to 2D array C#

后端 未结 4 1588
日久生厌
日久生厌 2020-12-01 22:18

I\'m trying to convert this function from Jagged Array to 2D array, and I\'m not able to convert everything Original Function:

public static double[][] Inver         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 22:44

    This snippet can be helpful

    static T[,] To2D(T[][] source)
    {
        try
        {
            int FirstDim = source.Length;
            int SecondDim = source.GroupBy(row => row.Length).Single().Key; // throws InvalidOperationException if source is not rectangular
    
            var result = new T[FirstDim, SecondDim];
            for (int i = 0; i < FirstDim; ++i)
                for (int j = 0; j < SecondDim; ++j)
                    result[i, j] = source[i][j];
    
            return result;
        }
        catch (InvalidOperationException)
        {
            throw new InvalidOperationException("The given jagged array is not rectangular.");
        } 
    }
    

    Usage:

    double[][] array = { new double[] { 52, 76, 65 }, new double[] { 98, 87, 93 }, new double[] { 43, 77, 62 }, new double[] { 72, 73, 74 } };
    double[,] D2 = To2D(array);
    

    UPD: For those scenarios where unsafe context is acceptable there is a faster solution, thanks Styp: https://stackoverflow.com/a/51450057/3909293

提交回复
热议问题