Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping a multidimensional array

I have the following class

class Tile
{
    public int height;
    public int terrain;
}

And I have a 2D array of Tiles

Tile[,] area = new Tile[5,5];

How could I map my area from a Tile[,] to a int[,], where only the height is saved?

I tried doing this:

area.Select(tile => tile.height)

but apparently C# Multidimensional arrays do not implement IEnumerable.

How could I solve this problem?

like image 474
Enrique Moreno Tent Avatar asked Dec 18 '22 01:12

Enrique Moreno Tent


1 Answers

How could I solve this problem?

By writing code. There's no "select" that works, so make your own:

static class Extensions 
{
  public static R[,] Select<T, R>(this T[,] items, Func<T, R> f) 
  {
    int d0 = items.GetLength(0);
    int d1 = items.GetLength(1);
    R[,] result = new R[d0, d1];
    for (int i0 = 0; i0 < d0; i0 += 1)
      for (int i1 = 0; i1 < d1; i1 += 1)
        result[i0, i1] = f(items[i0, i1]);
    return result;
  } 
}

And now you have the extension method you want.

EXERCISES:

  • Which of the standard LINQ sequence operators make sense to adapt to multidimensional arrays, and which do not?
  • Are there operators you'd like to see on multidimensional arrays that are not standard LINQ operators but which you could implement as extension methods?
like image 89
Eric Lippert Avatar answered Dec 20 '22 14:12

Eric Lippert