Generate a two dimensional array via LINQ

前端 未结 1 569
闹比i
闹比i 2020-12-11 01:55

I am trying to create a matrix of doubles, representing a correlation between entities.

Here\'s how I\'m doing it via LINQ

double[][] correlationsRaw         


        
相关标签:
1条回答
  • 2020-12-11 02:29

    I don't think there's an easy way of directly returning a multidimensional array from a Linq query... however you could create a function that takes a jagged array and return a multidimensional array :

    public T[,] JaggedToMultidimensional<T>(T[][] jaggedArray)
    {
        int rows = jaggedArray.Length;
        int cols = jaggedArray.Max(subArray => subArray.Length);
        T[,] array = new T[rows, cols];
        for(int i = 0; i < rows; i++)
        {
            cols = jaggedArray[i].Length;
            for(int j = 0; j < cols; j++)
            {
                array[i, j] = jaggedArray[i][j];
            }
        }
        return array;
    }
    

    By the way, it could be an extension method, allowing you to use it in a Linq query...

    0 讨论(0)
提交回复
热议问题