Search code examples
c#foreachienumerableienumerator

How to implement IEnumerator for map coordinates?


I find myself using the following pattern a lot when enumerating through all tile positions on a map:

for (int y = (int) map.Rect.y; y < map.Rect.yMax; y++)
    {
        for (int x = (int) map.Rect.x; x < map.Rect.xMax; x++)
        {
            // do something with X and Y coordinates
        }
    }

I've been studying IEnumerator and IEnumerable but I can't figure out how to implement them to the Map.

What I'd like to achieve:

foreach (Vector3Int position in Map)
    {
        DoSomething(position.x, position.y);
    }

And then Map can internally handle the rest of the logic, with this simpler syntax.


Solution

  • You can yield them:

    public IEnumerable<Point> AllMapPoints()
    {
        for (int y = (int) map.Rect.y; y < map.Rect.yMax; y++)
        {
            for (int x = (int) map.Rect.x; x < map.Rect.xMax; x++)
            {
                yield return new Point(x, y);
            }
        }
    }
    

    Now you can loop them all:

    foreach (var point in AllMapPoints())
    {
        DoSomething(point.X, point.Y);
    }
    

    or just some, for example:

    foreach (var point in AllMapPoints().Take(100))
    {
        DoSomething(point.X, point.Y);
    }