views:

373

answers:

5

I think this might be a pretty simple question, but I haven't been able to figure it out yet. If I've got a 2-dimensional array like so:

int[,] = new int[2,3] { {1, 2, 3}, {4, 5, 6} };

What's the best way to iterate through each dimension of the array with a nested foreach statement?

+2  A: 

With multidimensional arrays, you can use the same method to iterate through the elements, for example:

int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } };
foreach (int i in numbers2D)
{
    System.Console.Write("{0} ", i);
}

The output of this example is:

9 99 3 33 5 55

References


In Java, multidimensional arrays are array of arrays, so the following works:

    int[][] table = {
            { 1, 2, 3 },
            { 4, 5, 6 },
    };
    for (int[] row : table) {
        for (int el : row) {
            System.out.println(el);
        }
    }
polygenelubricants
C# has multidimensional and jagged arrays as seperate concepts, where `int[,]` is a 2 dimensional array, and `int[][]` is a jagged array of arrays and each given array is not required to have the same length. You can easily do a foreach on the jagged array, but a 2D array is not the same type of structure. At any rate, your second snippet doesn't fit *this* problem, the first snippet isn't nested.
Anthony Pegram
+2  A: 

Here's how to visit each element in a 2-dimensional array. Is this what you were looking for?

for (int i=0;i<array.GetLength(0);i++)
{
    for (int j=0;j<array.GetLength(1);j++)
    {
        int cell = array[i,j];
    }
}
Daniel Plaisted
I was hoping for a **foreach** implementation, if that's possible?
Tyler Murry
+2  A: 

The 2D array in C# does not lend itself well to a nested foreach, it is not the equivalent of a jagged array (an array of arrays). You could do something like this to use a foreach

foreach (int i in Enumerable.Range(0, array.GetLength(0)))
    foreach (int j in Enumerable.Range(0, array.GetLength(1)))
        Console.WriteLine(array[i, j]);

But you would still use i and j as index values for the array. Readability would be better preserved if you just went for the garden variety for loop instead.

Anthony Pegram
This is a horrible mutation of a classic, simple and understandable construct. If your code contains this, you really need to be thinking "hey, this works, but... how about not?" (I'm well aware this is idiomatic in the python family. However - This is C#.)
Rubys
@Rubys, this is not idiomatic in Python either. It is very unpythonic to get the indexes then access the list with `[]`. It is idiomatic Python to iterate over values directly. Also note that there are no multi-dimensional arrays or lists in Python (only jagged).
Matthew Flaschen
@Matthew: I may have confused python with another language, I don't really know my arms from my legs in the scripting family (which is what I meant in python family, I suppose)
Rubys
A: 

Two ways:

  1. Define the array as a jagged array, and use nested foreachs.
  2. Define the array normally, and use foreach on the entire thing.

Example of #2:

int[,] arr = { { 1, 2 }, { 3, 4 } };
foreach(int a in arr)
    Console.Write(a);

Output will be 1234. ie. exactly the same as doing i from 0 to n, and j from 0 to n.

Rubys
+2  A: 

If you want to iterate over every item in the array as if it were a flattened array, you can just do:

foreach (int i in array) {
    Console.Write(i);
}

which would print

123456

If you want to be able to know the x and y indexes as well, you'll need to do:

for (int x = 0; x < array.GetLength(0); x += 1) {
    for (int y = 0; y < array.GetLength(1); y += 1) {
        Console.Write(array[x, y]);
    }
}

Alternatively you could use a jagged array instead (an array of arrays):

int[][] array = new int[2][] { new int[3] {1, 2, 3}, new int[3] {4, 5, 6} };
foreach (int[] subArray in array) {
    foreach (int i in subArray) {
        Console.Write(i);
    }
}

or

int[][] array = new int[2][] { new int[3] {1, 2, 3}, new int[3] {4, 5, 6} };
for (int j = 0; j < array.Length; j += 1) {
    for (int k = 0; k < array[j].Length; k += 1) {
        Console.Write(array[j][k]);
    }
}
ICR
After seeing the err of my ways (e.g. trying to use a 2D array like a jagged array), I agree the best way to iterate through that list is just like you have it in your first example. You get the vote because of your willingness to go beyond the answer and give other options.
Tyler Murry