Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For Each loop on a 2D array in VB.NET

I'm writing a loop to go through the first array of a 2D loop, and I currently have it like this:

For Each Dir_path In MasterIndex(, 0)
    'do some stuff here
Next

But it's giving me an error, saying it expects an expression in the first field. But that's what I'm trying to do, loop through the first field. How do I fix this? What would I put in there?

EDIT: to clarify, I'm specifically looking for the 0th element in the subarray of each array, that's why that second field is constantly 0.

like image 458
jayjyli Avatar asked Oct 14 '11 15:10

jayjyli


1 Answers

You can use Enumerable.Range recursively to iterate the dimensions of an array.

Lets say we have a two dimensional grid (rows and columns) of Int.

We can iterate it as follows:

using System.Linq;

[TestMethod]
public void TestTwoDimensionalEnumeration()
{
    int rowcount = 9;
    int columncount = 9;
    int[,] grid = new int[rowcount, columncount];
    var enumerated =
        Enumerable.Range(0, rowcount - 1).
        SelectMany(ri => Enumerable.Range(0, columncount - 1).
        Select(ci => new {
                            RowIndex = ri,
                            ColumnIndex = ci,
                            Value = grid[ri,ci]
                         }));
    foreach (var item in enumerated)
    {
        System.Diagnostics.Trace.WriteLine("Row:" + item.RowIndex + 
                                          ",Column:" + item.ColumnIndex + 
                                          ",Value:" + item.Value);
    }
}

The same logic can be applied to any number of dimensions.

like image 156
Cogent Avatar answered Oct 16 '22 16:10

Cogent