通过LINQ生成二维数组 [英] Generate a two dimensional array via LINQ
问题描述
我正在尝试创建一个双精度矩阵,以表示实体之间的相关性.
I am trying to create a matrix of doubles, representing a correlation between entities.
这是我通过LINQ进行的方式
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();
那很好.
但是我想要的是二维数组( double [,] ),而不是锯齿状的数组.
But what I want is a two dimensional array (double[,]), not a jagged array.
很明显,我可以编写一些嵌套的 for 循环将一个转换为另一个.
Obviously, I can write some nested for loop to convert one into the other.
但是我可以在这里使用一些优雅的LINQ技巧吗?
But is there some elegant LINQ trick I can use here?
推荐答案
我认为没有简单的方法可以直接从Linq查询返回多维数组...但是您可以创建一个带有锯齿形数组的函数并返回一个多维数组:
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;
}
顺便说一句,它可能是一种扩展方法,允许您在Linq查询中使用它...
By the way, it could be an extension method, allowing you to use it in a Linq query...
这篇关于通过LINQ生成二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!