0

I keep going through a two dimensional array and would like to stop repeating the same nested for loops

for (int x = 0; x < width; x++) {
  for (int y =0; y < height; y++) {
    // Do some stuff
  }
}

Is there a way to DRY-out the nested for loops to something more along the lines of

iterateThroughMatrix ( doSomeStuff )
iterateThroughMatrix ( doSomethingElse )
iterateThroughMatric ( doSomeOtherStuff )

void iterateThroughMatrix ( doSomething ) {
  for (int x = 0; x < width; x++) {
    for (int y =0; y < height; y++) {
      // doSomething here
    }
  }
}
D.Pod
  • 5
  • 1
  • 3
  • Take a look at [how to pass methods as parameter](http://stackoverflow.com/questions/2082615/pass-method-as-parameter-using-c-sharp) – D. Petrov Jul 16 '16 at 05:05

1 Answers1

3

You need something like this:

void iterateThroughMatrix(Action<int, int> doSomething)
{
    for (int x = 0; x < width; x++)
    {
        for (int y = 0; y < height; y++)
        {
            doSomething(x, y);
        }
    }
}

You can use any delegate that has two integers, but Action<int, int> is built-in and ready to go.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172