通过 LINQ 生成二维数组 [英] Generate a two dimensional array via LINQ

查看:24
本文介绍了通过 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆