I've got a two-dimensional array,
string[,] table = { { "aa", "aaa" }, { "bb", "bbb" } };
And I'd like to foreach
through it like this,
foreach (string[] row in table) { Console.WriteLine(row[0] + " " + row[1]); }
But, I get the error:
Can't convert type string to string[]
Is there a way I can achieve what I want, i.e. iterate through the first dimension of the array with the iterator variable returning me the one-dimensional array for that row?
Since 2D arrays are really arrays of arrays you can also use a nested enhanced for-each loop to loop through all elements in an array. We loop through each of the inner arrays and loop through all the values in each inner array.
For example, write the foreach loop where the $bikes variable is the array. Set the $number variable as key and the $bike variable as value. Next, write another foreach loop inside the just created loop. In the nested loop, write the $bike variable as an array and set the $num and $value as key and value.
You will have to use nested loops. The outer loop accesses the rows of the array, while the inner loop accesses the elements within that row. Then, just print it out and start a new line for every row (or choose whatever format you want it to be printed in).
The foreach loop also works on multidimensional arrays. It returns those elements in row order, from first to last. The output from this program is shown here:
Multidimensional arrays aren't enumerable. Just iterate the good old-fashioned way: Show activity on this post. As others have suggested, you could use nested for-loops or redeclare your multidimensional array as a jagged one. However, I think it's worth pointing out that multidimensional arrays are enumerable, just not in the way that you want.
A foreach loop is only used to iterate over such arrays and is the easiest and simplest way to do so. The foreach loop iterates through each index starting from 0. If there are multiple statements within the foreach loop, they have to be enclosed with begin and end keywords like all other procedural blocks.
SystemVerilog foreach loop SystemVerilog arrays are data structures that allow storage of many values in a single variable. A foreach loop is only used to iterate over such arrays and is the easiest and simplest way to do so.
Multidimensional arrays aren't enumerable. Just iterate the good old-fashioned way:
for (int i = 0; i < table.GetLength(0); i++) { Console.WriteLine(table[i, 0] + " " + table[i, 1]); }
As others have suggested, you could use nested for-loops or redeclare your multidimensional array as a jagged one.
However, I think it's worth pointing out that multidimensional arrays are enumerable, just not in the way that you want. For example:
string[,] table = { { "aa", "aaa" }, { "bb", "bbb" } }; foreach (string s in table) { Console.WriteLine(s); } /* Output is: aa aaa bb bbb */
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With