I would like to iterate the rows and columns separately on a two dimensional array:
object[,] values;
How would I iterate through just the rows and just the columns?
In order to loop over a 2D array, we first go through each row, and then again we go through each column in every row. That's why we need two loops, nested in each other. Anytime, if you want to come out of the nested loop, you can use the break statement.
In each iteration we output a column out of the array using ary[:, col] which means that give all elements of the column number = col. METHOD 2: In this method we would transpose the array to treat each column element as a row element (which in turn is equivalent of column iteration).
Since 2D arrays are really arrays of arrays you can also use a nested enhanced for-each loop to loop through all elements in an array.
Now let's jump into nested for loops as a method for iterating through 2D arrays. A nested for loop is one for loop inside another.
It depends what's columns and rows for you but you could use this snippet of code:
for (int i = 0; i < values.GetLength(0); i++)
Console.WriteLine(values[i, 0]);
And:
for (int i = 0; i < values.GetLength(1); i++)
Console.WriteLine(values[0, i]);
Here's some code to iterate through the first and second dimensions of the array a 2 dimensional array. (There aren't really "rows" and "columns" because a multidimensional array can have any number of dimensions)
object[,] values = new object[5,5];
int rowIWant = 3; //Make sure this is less than values.GetLength(0);
//Look at one "row"
for(int i = 0; i < values.GetLength(1); i++
{
//Do something here with values[rowIWant, i];
}
int columnIWant = 2; //Make sure this is less than values.GetLength(1);
//Look at one "column"
for(int i = 0; i < values.GetLength(0); i++
{
//Do something here values[i, columnIWant];
}
Multi-dimensional arrays don't have rows and columns in the way you're referring to them - they just have several indexes used to access values. Iterating over such an array would be done using nested for-loops, and if you want to perform certain calculations on a per-dimension base you should alter the order of the loops accordingly.
Another option, if you only need to iterate over one dimension, is to use an array of arrays instead of a multi-dimensional array like this:
object[][] values;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With