Multidimensional array index lookup in a foreach loop

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Jaxe
    New Member
    • Oct 2009
    • 2

    Multidimensional array index lookup in a foreach loop

    Code:
    Item[,] itemArray;
    
    // initialising code here
    // fill with data
    
    foreach (Item item in itemArray)
    {
    // I need to access the [x,y] indexes here:
    // x_index = ??
    // y_index = ??
    // item.DoSomething(x_index, y_index);
    }
  • tlhintoq
    Recognized Expert Specialist
    • Mar 2008
    • 3532

    #2
    You could do it with a foreach, but given your needs it is is probably easier to you a for with an int counter

    Code:
    for (int x = 0; x < YourXcounter; x++)
    {
       for (int y = 0; y < YourYcounter; y++)
       {
          Item ThisItem = Item[x,y];
          // Do something with ThisItem
       }
    }

    Comment

    • Jaxe
      New Member
      • Oct 2009
      • 2

      #3
      Thanks for the reply.

      I'm currently using nested for loops, but they tend to get a bit messy when working with arrays of 3 or more dimensions.

      Is there anyway to get it working with the foreach syntax?

      I'm looking for something that returns the index for a given dimension.

      GetIndex is imaginary here:

      Code:
      foreach (Item item in itemArray)
      {
      x_index = item.GetIndex(0); // returns x index
      y_index = item.GetIndex(1); // returns y index
      z_index = item.GetIndex(2); // returns z index
      item.DoSomething(x_index, y_index, z_index);
      }

      Comment

      Working...