如何将 3 维数组复制到 2 维数组?

问题描述 投票:0回答:2

我想从 3 维数组的第一个索引复制一部分到 2 维数组。
像这样

string[,] array2d = new string[9, 9];

array2d = array3d [0,,];

我习惯于在可能的地方使用 php。

我试过进一步寻找但找不到任何东西

c# arrays multidimensional-array
2个回答
0
投票

如果您正在寻找 compact 语法,您可以从 n-d 数组切换到锯齿状数组:

string[][][] array3d = ...

string[][] array2d = array3d[0];

如果你必须坚持使用 n-d 数组,你必须编写更多代码并手动复制项目:

string[,,] array3d = ...

string[,] array2d = new string[array3d.GetLength(1), array3d.GetLength(2)];

for (int i = 0; i < array2d.GetLength(0); ++i)
  for (int j = 0; j < array2d.GetLength(1); ++j)
    array2d[i, j] = array3d[0, i, j];

0
投票

如果你作为源数组的是一个实际的 3 维数组,那么你想要的是不支持的。多维数组的索引器有多个参数。这意味着,您需要在尝试访问它们上的元素时全部传递它们。

但是,您实际上可以通过手动从 3d 数组复制到 2d 数组来完成所需的操作。为了使其更具可重用性,您可以将此行为封装在一个扩展方法中,该方法将抽象掉它并使您的代码更清晰和可读。

public static class ArrayExtensions
{
    public static T[,] Extract2DArray<T>(this T[,,] array3d, int index = 0)
    {
        var dim0Length = array3d.GetLength(0);
        if (index < 0 || index >= dim0Length)
            throw new ArgumentOutOfRangeException(nameof(index), index, $"The index to extract from the 3-d array is out of range. Must be in the range [{0}..{dim0Length - 1}]");

        var dim1Length = array3d.GetLength(1);
        var dim2Length = array3d.GetLength(2);
        T[,] array2d = new T[dim1Length, dim2Length];
        for (int i = 0; i < dim1Length; i++)
            for (int j = 0; j < dim2Length; j++)
                array2d[i, j] = array3d[index, i, j];

        return array2d;
    }
}

有了上面的内容,你可以像这样使用它:

string[,,] array3d = new string[,,]
{
    {
        { "one", "two", "three" },
        { "four", "five", "six" },
        { "seven", "eight", "nine" },
    },
    {
        { "ten", "eleven", "twelve" },
        { "thirdteen", "fourteen", "fifteen" },
        { "sixteen", "seventeen", "eighteen" }
    },
    {
        { "nineteen", "twenty", "twenty one" },
        { "twenty two", "twenty three", "twenty four" },
        { "twenty five", "twenty six", "twenty seven" }
    }
};

// Extract the first index:
var first2dArray = array3d.Extract2DArray(0);

// Extract the last 2d array
var last2dArray = array3d.Extract2DArray(2);

// Trying to use this with invalid indexes would throw an exception
var invalidIndexArray = array3d.Extract2DArray(3); // a negative index will fail too

Exception: The index to extract from the 3-d array is out of range. Must be in the range [0..2] (Parameter 'index')
Actual value was 3.
© www.soinside.com 2019 - 2024. All rights reserved.