#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

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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

  1. Pingback: Dew Drop – June 24, 2014 (#1802) | Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: