Here’s an extension method each which can be used to apply an Action<int, int, T> to every element and it’s corresponding indices of a two-dimensional array:
static public void each<T>(this T[,] a, Action<int, int, T> proc)
{
for (int i = 0; i < a.GetLength(0); i++)
for (int j = 0; j < a.GetLength(1); j++)
proc(i, j, a[i, j]);
}
Example usage:
var arr = new int[3, 3];
arr.each((x, y, val) => arr[x, y] = x + y);
arr.each((x, y, val) => Console.WriteLine("{0} {1} {2}", x, y, val));
Is it possible to write a version of each which can work on arrays of any rank?
There’s no way to specify a generic with an arbitrary number of parameters, so you would have to pass your procedure an array of indices. The easiest way to do this is probably with recursion so here’s a recursive way to do it. Since it uses an optional parameter it requires C# 4.0 or higher.
You would call it like this: