#1,124 – Iterate through Jagged Array with Nested foreach

You can’t use the foreach statement to directly iterate over all elements in a jagged array.  You can, however, iterate through the jagged array using nested foreach statements.  Each foreach statement independently iterates over one dimension of the jagged array.

            // Jagged array - 3 elements, each of which is array of int
            int[][] nums = new int[3][];

            nums[0] = new int[4];
            nums[2] = new int[3];

            for (int i = 0; i < 4; i++)
                nums[0][i] = i + 1;

            for (int i = 0; i < 3; i++)
                nums[2][i] = i + 101;

            // Iterate using foreach
            foreach (int[] intArray in nums)
            {
                if (intArray != null)
                {
                    Console.WriteLine("Array with {0} elements", intArray.Length);
                    foreach (int n in intArray)
                        Console.WriteLine("  {0}", n);
                }
                else
                    Console.WriteLine("Found null array");
            }

1124-001

Advertisements