使用LINQ获取多维数组的分区

使用LINQ获取多维数组的分区

本文介绍了使用LINQ获取多维数组的分区(N维数组的(N-1)维实例)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从3d数组中获取2d数组.假设我有一个尺寸为[10,10,10]的双3d数组A3
我需要得到一个二维数组A2 = A3 [:,5 ,:],即第二维的索引等于5.

I want to get a 2d array from a 3d array. Let's say I have a double 3d array A3 of dimension [10,10,10]
I need to get a 2d array A2 = A3[:,5,:], i.e. where the index of the second dimension is equal to e.g. 5.

如果我想获得2d数组A2(即2d数组的1d实例)的分区(例如A1 = A2 [2 ,:]类型的分区),我可以这样做(第一维的索引)设置为例如2):

If I want to get the partition (for instance of the kind A1=A2[2,:]) of 2d array A2 (i.e. 1d instance of 2d array) I can do this (the index of the 1-st dimensional is set e.g. to 2):

double[] A1 = Enumerable.Range(0,A2.Length).Select(x=>A2[2,x]).ToArray();

我该如何从3维扩展到2维(或者通常从N维扩展到N-1维)?

How can I do it going from 3 to 2 (or generally from N to N-1) dimensions?

修改.输入示例:

double[,,] A3 = new double[2,3,4]{
            {
                {4,3,2,1},
                {5,4,3,2},
                {6,5,4,3}
            },
            {
                {1,2,3,4},
                {2,3,4,5},
                {3,4,5,6}
            }
        };

结果数组A2 = A3 [:,1 ,:]内部必须具有以下内容:{{5,4,3,2},{2,3,4,5}}

The result array A2=A3[:,1,:] must have the following inside: { {5,4,3,2},{2,3,4,5} }

推荐答案

LINQ通常不适用于多维数组.这些操作本质上是一维的.嵌套一维数组的效果要好得多,因此,如果要返回深度为2的锯齿状数组,即 double [] [] 而不是 double [,] LINQ是更合适的工具.

LINQ in general doesn't play too well with multi-dimensional arrays. The operations are inherently single dimensional. It plays much better with nested single dimensional arrays, so if you wanted to return a jagged array of depth two, i.e. a double[][] rather than a double[,] LINQ is a more appropriate tool.

public static T[][] GetPlane<T>(T[, ,] source, int secondDimensionValue)
{
    return Enumerable.Range(0, source.GetLength(0))
        .Select(i => Enumerable.Range(0, source.GetLength(2))
            .Select(j => source[i, secondDimensionValue, j])
            .ToArray())
        .ToArray();
}

这篇关于使用LINQ获取多维数组的分区(N维数组的(N-1)维实例)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 07:02