Skip to content

Instantly share code, notes, and snippets.

@dharmatech
Created November 18, 2011 04:42
Show Gist options
  • Select an option

  • Save dharmatech/1375626 to your computer and use it in GitHub Desktop.

Select an option

Save dharmatech/1375626 to your computer and use it in GitHub Desktop.

Traversing two-dimensional arrays (C#)

The System.Array class provides ForEach which can be used to traverse one-dimensional arrays. Here are some utilities for working with two-dimensional arrays.

each

Given a two-dimensional array, each applies an Action<int, int, T> to every element and its corresponding indices.

    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));

Here's a variant which applies an Action<T> to the elements only. It's in terms of the general each shown above.

    static public void each<T>(this T[,] a, Action<T> proc)
    {
        a.each((x, y, val) => proc(val));
    }

Example usage:

var arr = new int[3, 3];

arr.each((x, y, val) => arr[x, y] = x + y);

arr.each((val) => Console.WriteLine("{0}", val));

map

map builds a new two-dimensional array by applying a Func<int, int, T, T> to the elements and indices of an array. map is written in terms of the general each.

    static public T[,] map<T>(this T[,] a, Func<int, int, T, T> proc)
    {
        var b = new T[a.GetLength(0), a.GetLength(1)];

        a.each((x, y, val) => b[x, y] = proc(x, y, val));

        return b;
    }

Here's a variant which applies a Func<T, T> to the elements only:

    static public T[,] map<T>(this T[,] a, Func<T, T> proc)
    {
        var b = new T[a.GetLength(0), a.GetLength(1)];

        a.each((x, y, val) => b[x, y] = proc(val));

        return b;
    }

map_in_place

map_in_place doesn't return a new array. Instead, it overwrites values as it generates them.

    static public void map_in_place<T>(this T[,] a, Func<int, int, T, T> proc)
    {
        a.each((x, y, val) => a[x, y] = proc(x, y, val));
    }

The element-only variation:

    static public void map_in_place<T>(this T[,] a, Func<T, T> proc)
    {
        a.each((x, y, val) => a[x, y] = proc(val));
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment