【问题标题】:C# - Get multi-dimensional slice of array in VERTICAL collectionsC# - 在 VERTICAL 集合中获取数组的多维切片
【发布时间】:2016-05-25 18:24:52
【问题描述】:

我有一个使用多维数组数据结构的程序。数据被分配到多维数组中,一次一个数组(或行)(使用for 循环)。

例如,数组包含以下值:

double[][] values = new double[][]
{
    {0.0, 0.1, 0.2, 0.3}, //each row added as 1
    {1.0, 1.1, 1.2, 1.3},
    {2.0, 2.1, 2.2, 2.3},
    {3.0, 3.1, 3.2, 3.3}
};

在程序中的某些点,需要根据某些变量中保存的值返回多维数组的子集。但是,这需要将数组数据分组为列而不是行。

例如,像这样的:

//two dimensional array function to return subset of 'values'
public double[][] getArrayData(int startIndex, int endIndex)
{
    //for sake of example, assume startIndex = 1, endIndex = 2
    //returned structure would need to have the following values...
    {0.1, 1.1, 2.1, 3.1}, //all values in 'row' with index 1
    {0.2, 1.2, 2.2, 3.2}  //all values in 'row' with index 2

    //returns this 2D array
}

这实际上是将行数据转换为列数据,我预计这可以使用某种双 for 循环来完成。

有谁知道如何达到这个结果?

谢谢,

标记

【问题讨论】:

  • 你能在.NETFiddle上添加一个样本吗?
  • dotnetfiddle.net/dbtgIm 我已经把它放在这里了,我只需要定义函数来完成预期的工作!谢谢@aloisdg
  • 我开始认为我误解了您的要求。你想做什么?
  • 您必须使用循环并通过手术获取列值。您拥有的结构可以轻松获取 row 的切片,但不能轻松获取 column。 C# 中没有内置的数据结构可以轻松让您获取行或列切片。

标签: c# arrays multidimensional-array


【解决方案1】:

您可以使用 LINQ 执行此操作而无需循环。

public static double[][] getArrayData(double[][] values, int startIndex, int endIndex)
{
    return 
        Enumerable.Range(startIndex, endIndex)
            .Select(i => values.Select(x => x[i])
            .ToArray()
        ).ToArray();
}

JSFiddle

【讨论】:

    【解决方案2】:

    检查这个fiddle,我做了两个函数,一个翻转数组,另一个获取指定的行。我不确定您具体在寻找什么,但两者的结合应该可以。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    • 2021-11-23
    相关资源
    最近更新 更多