Thomas Z

Hi. I'm playing around with multidimensional arrays and think I'm a little confused on some things. Basically, I'm wondering if its possible to access a row (or column) in an MD array and treat it like a single dimensional array for purposes of parameters. So, suppose I have this method:

public static void processSingleArray(int[] arr) {
// ..for each item in arr, doStuff.
}

I can do this fine:

int[] Array1 = { 3, 4, 5 };
processSinglleArray(Array1);

But now, suppose I wanted to run this method with a row or column of a multidimensional array. I've always thought of multidimensional arrays as arrays of arrays, so it seems I could do something like this:

int[,] Array2 = { {2, 3}, {3, 23} };
processSingleArray(Array2[ 1, ]; // intent is to process on the column of index 1.
processSingleArray(Array2[ , 0 ]; // intent is to process on the row of index 2.

or, maybe:
processSingleArray(Array2.ItemsAtColumn(1));
processSingleArray(Array2.ItemsAtRow(0));

and obviously, neither of these are compiling. I'm not sure of the syntax to pass the items at a specified index in the way I'd like. I know I could write code to cycle through each row and column in the 2d array, but i'd like this to work on arrays of even more dimensions too, without duplicating code effort. I don't think this should be too hard, but couldn't really find any answers in the help files, either.


Re: Visual C# General Accessing rows/columns in MultiDimensional Arrays

Kenny99

Multi dimensional arrays declared as

Code Block
int[,] Array2 = { {2, 3}, {3, 23} };

should not be thought of 'arrays of arrays', but mor like a fixed matrix of int (or objct etc) where you access elemts by specifying "row" and "column" (or however you wish to name the dimensions. To get an array of arrays you want a jagged array, which is declared as follows:

Code Block

int[][] jaggedArray = { new int[] {1,2,3,4},
new int[] {5,6,7},
new int[] {8},
new int[] {9}
};


One of the main differences is that each of the arrays in the jagged array can vary in size. A jagged array will give you the functionality you require;

i.e:

Code Block
int
[] oneDimArray = jaggedArray[1];

more information can be found at http://msdn2.microsoft.com/en-us/library/ms182277(vs.80).aspx

Hope this helps,

Kenny





Re: Visual C# General Accessing rows/columns in MultiDimensional Arrays

Thomas Z

Thanks. Jagged arrays def. seem to be more what I was looking for, though the non-uniform length is a little frustrating.

One other hypothetical - given a multidimensional array, is there even a way to tell how many rows/ columns it has This code:

int[,] Array2 = { {2, 3}, {3, 23} };
Console.WriteLine(Array2.Length);

obviously just prints out 4.




Re: Visual C# General Accessing rows/columns in MultiDimensional Arrays

Tergiver

Since it is up to you to define the width of a multidimensional array, you can simply divide by that width.