+ 1

Using the foreach loop construct in C#

static void Main(string[] args) { int[ , ] someNums = { {2, 3}, {5, 6}, {4, 6} }; int outerRow = 1; foreach (var outer in someNums) { Console.WriteLine("outer row: {0}\n\n", outerRow); ***this line fails--> foreach (var inner in outer) { Console.WriteLine(" inner value: {0}", inner); }//foreach inner outerRow += 1; }//foreach outer }//Main C# compiler complains that a variable of type int doesn't have a publicly defined GetEnumerator() method, or something like that. To me, the outer foreach loop returns a reference to each of the subarrays in someNums. Then the inner foreach loop is supposed to iterate through the elements of the subarray and print them to the Console. Obviously, I have missed something fundamental. Can anyone help me correct my code? Thank you! EDIT: Oops! I blocked out the inner foreach loop and ran the program. Seems that the outer foreach actually enumerates all of the elements in all of the subarrays. It doesn't enumerate a whole subarray at a time. So I guess my question now is, how do I iterate through someNums so that I get a reference to each one of the subarrays, not the individual constituent array elements? Is this even possible? Thank you!

8th Dec 2017, 1:06 AM
Adiv Abramson
Adiv Abramson - avatar
1 Réponse
+ 1
You either have to use jagged arrays to use a for loop as far as I can tell. https://code.sololearn.com/cx7eQvh0m7O6/?ref=app
8th Dec 2017, 2:14 AM
Jesse Bayliss
Jesse Bayliss - avatar