简体   繁体   中英

C# - Get multi-dimensional slice of array in VERTICAL collections

I have a program that uses a multidimensional array data structure. The data is assigned into the multidimensional array, one single array (or row) at a time (using a for loop).

Say for example, the array contains the following values:

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}
};

At some points in the program, a subset of the multidimensional array will need to be returned depending on the values held in certain variables. However, this will need to group the array data in columns rather than rows.

For example, something like this:

//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
}

What this essentially does is turn row data into column data, which I anticipate can be done using a double for loop of some kind.

Does anyone know how this result can be reached?

Thanks,

Mark

You can use LINQ to do this without a loop.

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

Check this fiddle , I have made 2 functions, one that flips the array, and the other that gets the specified rows. I'm not sure what you're specifically looking for, but the combination of the two should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM