How do I 'foreach' through a two-dimensional array?

Scott Langham picture Scott Langham · May 14, 2010 · Viewed 115.4k times · Source

I've got a two-dimensional array,

string[,] table = {
                       { "aa", "aaa" },
                       { "bb", "bbb" }
                   };

And I'd like to foreach through it like this,

foreach (string[] row in table)
{
    Console.WriteLine(row[0] + " " + row[1]);
}

But, I get the error:

Can't convert type string to string[]

Is there a way I can achieve what I want, i.e. iterate through the first dimension of the array with the iterator variable returning me the one-dimensional array for that row?

Answer

Marcelo Cantos picture Marcelo Cantos · May 14, 2010

Multidimensional arrays aren't enumerable. Just iterate the good old-fashioned way:

for (int i = 0; i < table.GetLength(0); i++)
{
    Console.WriteLine(table[i, 0] + " " + table[i, 1]);
}