Quantcast
Channel: 2,000 Things You Should Know About C# » foreach
Viewing all articles
Browse latest Browse all 10

#1,123 – Using foreach to Iterate on a Multidimensional Array

$
0
0

You can use the foreach statement to iterate through all elements in a multidimensional array.  The elements are iterated in a row-major order.  That is, all elements in the first row are enumerated, followed by the second row, etc.

            // 2-dimensional array
            string[,] twoByThree = new string[2, 3];

            // Populate with standard for loop
            for (int row = 0; row < 2; row++)
                for (int col = 0; col < 3; col++)
                    twoByThree[row, col] = string.Format("{0}/{1}", row + 1, col + 1);

            // Iterate using foreach
            foreach (string s in twoByThree)
                Console.WriteLine(s);

1123-001


Filed under: Statements Tagged: Array, C#, foreach, Statements

Viewing all articles
Browse latest Browse all 10

Trending Articles