I have a class (Biome
) which contains a 2D array of custom objects (Level
). I frequently want to loop through all (or some) of the levels and perform some actions, e.g. set their colour property.
Rather than writing the same nested for-loop over and over again, can I make my own method which will let me do something like: ForEachLevel(SetColour())
?. Where SetColour()
would be a method in my Biome
class which just sets the Level's colour property to some random value or using some other logic based on factors within the Biome
?
So instead of:
for (int r = 0; d < Rows; r++)
{
for (int c = 0; l < Cols; c++)
{
if (some logic here)
Levels[r, c].Colour = Color.Red;
else
Levels[r, c].Colour = Color.Green;
}
}
I could do something like:
ForEachLevel(SetColour(--what goes here?--));
void SetColour(Level level){
if (some logic here)
level.Colour = Color.Red;
else
level.Colour = Color.Green;
}
Or even better, I'd like to make something similar which only runs a function on, say, rows X through to Y.
As you can see from my example I don't even know how I'd get the context of each Level instance into the SetColour function.
I can keep copy/pasting my custom nested for-loops to achieve what I want, but I was hoping someone with more experience might be able to understand what I'm trying to do and point me to the right direction on how I can use better C# techniques.
Because I've been vague I understand if a specific answer cannot be given, but some key concepts for further research would be appreciated!! Thanks
EDIT2 actually that previous attempt doesnt work at all. I forgot I need to actually call ForEachLevel somewhere else. Still working on it.
private void SomeOtherMethod()
{
// where I want to actually use the ForEachLevel()
ForEachLevel(SetLevelColor(--Level??--, Color.red));
}
private void ForEachLevel(Action DoAThing)
{
for (int d = 0; d < Depths; d++)
{
for (int l = 0; l < Lanes; l++)
{
DoAThing();
}
}
}
private void SetLevelColor(Level level, Color color)
{
// trivial example
level.Color = color;
}