Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get sub array from a 3D array

Tags:

arrays

c#

If I have an array:

int[,,] mainArray = new int[10,10,3];

How can I get a sub array:

int[] sub = mainArray[0,1]; // Unfortunately this doesn't work

Where sub would contain the 3 elements

sub[0] = mainArray[0,1,0];
sub[1] = mainArray[0,1,1];
sub[2] = mainArray[0,1,2];

It would be easy to write a method to do this but is there a built in way to do it?

like image 394
Juicy Avatar asked Feb 18 '14 01:02

Juicy


People also ask

How do you get a sub array from an array?

slice() The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified. Basically, slice lets you select a subarray from an array.

How do I extract a sub array in Python?

To get the subarray we can use slicing to get the subarray. Step 1: Run a loop till length+1 of the given list. Step 2: Run another loop from 0 to i. Step 3: Slice the subarray from j to i.


1 Answers

I think you can use an extension method like this:

public static class MyExtensions
{
    public static int[] GetValues(this Array source, int x, int y)
    {
        var length = source.GetUpperBound(2);
        var values = new int[length+1];
        for (int i = 0; i < length+1; i++)
        {
            values[i] = (int)source.GetValue(x, y, i);
        }
        return values;
    }
}

Usage:

int[,,] mainArray = new int[10,10,3];
int[] sub = mainArray.GetValues(0, 1);
like image 58
Selman Genç Avatar answered Oct 02 '22 03:10

Selman Genç