I am working with multi-dimentioned arrays of bool, int, and various struct. The code loops through these arrays and performs some operation on specific values. For instance,
for (int x = 0; x < this.Size.Width; x++) {
for (int y = 0; y < this.Size.Height; y++) {
if (this.Map[x, y]) {
DrawTerrain(this.Tile[x, y].Location, Terrain.Water);
}
}
}
I can do simple LINQ stuff, but I can’t do what I would like. What I would like to do is use LINQ. Maybe something like
from x in this.Map where x == true execute DrawTerrain(...)
But, I don’t understand how I can get the x and y locations or how to call a method in the LINQ statement.
Also, it would be great if I can put this code into a function and be able to call it with a delegate or a predicate? I don’t know if delegate or predicate are the correct words.
void Draw(Delegate draw, bool[,] map, struct[,] tiles)
from x in map where x == true draw(titles[x,y]).invoke;
}
The LINQ query syntax isn’t really designed for working with 2-dimensional data structures, but you can write an extension method that will convert the 2D array into a sequence of values that contain the coordinates in the original 2D array and the value from the array. You’ll need a helper type to store the data:
Then you can write the extension method (for any 2D array) like this:
Now you can finally start using LINQ. To get coordinates of all elements from the 2D array such that the value stored in the element is
true, you can use the following:This lets you specify some interesting conditions when filtering the tiles. For example if you wanted to get only diagonal elements, you could write:
To answer your second question – if you want to encapsulate the behavior into the method, you’ll probably need to use some
Action<...>delegate to represent the drawing function that will be passed to the method. It depends on the type signature of your drawing method though.