Trying to iterate over arrays through foreach : Error

 int[][] anArray = {new int[] {123,432}, new int[] {543,542}}; foreach (int i in anArray) //ошибка foreach (int j in anArray[i]) Console.WriteLine(anArray[i][j]); Console.ReadKey(); 

But when iterating through for everything is fine

 int[][] anArray = {new int[] {123,432}, new int[] {543,542}}; for (int i = 0; i < anArray.Length; i++) for (int j = 0; j < anArray[i].Length; j++) Console.WriteLine(anArray[i][j]); Console.ReadKey(); 

What's the matter?

  • 3
    Because an array of arrays, suddenly, is an array of arrays, not ints - Andrey NOP
  • what error? - Grundy

4 answers 4

Replace int with var in foreach .

You have an array of arrays => there int[]

  • But only? This is not enough - Andrew NOP

Right:

 foreach (int[] arr in anArray) foreach (int x in arr) Console.WriteLine(x); 

The foreach used to iterate through the collection (or sequence) and at each step it returns the next element of a particular collection (sequence).
The for loop is more universal, at each iteration it simply changes a certain variable (or several variables, or does not change anything) according to a certain rule, and also checks certain boundary conditions (or does not check anything), in particular, you change in cycles for i , j variables that you use as an array index.

You have an array of arrays, so the external foreach returns in turn all the "internal" arrays from the "external" array.

    Another method may suit you:

     foreach (int v in anArray.SelectMany(x => x)) Console.WriteLine(v); 
       int[][] anArray = {new int[] {123,432}, new int[] {543,542}}; foreach (int[] i in anArray) { // anArray содСрТит 2ΠΌΠ΅Ρ€Π½Ρ‹ΠΉ массив, Π·Π½Π°Ρ‡ΠΈΡ‚ i Π΄ΠΎΠ»ΠΆΠ΅Π½ Π±Ρ‹Ρ‚ΡŒ массивом, Π° Π½Π΅ элСмСнтом. foreach (int j in i) { Console.WriteLine(j); } }