Search code examples
c#foreachnested-loops

Iterate Multi-Dimensional Array with Nested Foreach Statement


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[,] array = 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?


Solution

  • 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]);
        }
    }