Generate a two dimensional array via LINQ

人走茶凉 提交于 2019-12-28 20:03:53

问题


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 = (from e in entitiesInOrder
                              select
                                (from f in entitiesInOrder
                                     select correlations.GetCorrelation(e, f)
                                ).ToArray()).ToArray();

That works fine.

But what I want is a two dimensional array (double[,]), not a jagged array.

Obviously, I can write some nested for loop to convert one into the other.

But is there some elegant LINQ trick I can use here?


回答1:


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...



来源:https://stackoverflow.com/questions/1781172/generate-a-two-dimensional-array-via-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!