4

Give I have a 3D map of type whose the length and width are uniform but the depth is jagged:

public class Map<T>
{
    T[,][] map;
    ...
}

What is the best way to return a 1D array of all of the objects of type that exist within a volume defined by a 2D area and all of depth within that area. For example I might have an array notation override as follows:

public IEnumerable<T> this[Rectangle area]
{
    get {...}
}

or just

public IEnumerable<T> this[int x, int y, int width, int length]
{
    get {...}
}

I am honestly hoping for an fast LINQ solution but performance is preferable to visual elegance of the solution. The order of the objects within the flattened array that is returned is unimportant. If anyone has any suggestions or experience with this please share your wisdom.

Alternatively if there is another data structure at my disposal that can perform the same function that I am unaware of, I will gladly use that instead.

If something about my question is unclear please ask for further details.

2 Answers 2

2

Are you looking for something like this?

public IEnumerable<T> this[int left, int top, int width, int height]
{
    get
    {
        return from x in Enumerable.Range(left, width)
               from y in Enumerable.Range(top, height)
               from i in this.map[x, y]
               select i;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This solution works great but is slightly slower than the for loop solution. Only slightly. When iterating over an 4700x4700 area this solution was clocked 3.4 seconds while the for loop solution was 1.7 seconds.
1

This might work as well (without Linq)

    public IEnumerable<T> this[int x, int y, int width, int length]
    {
        get
        {
            for (int i = 0; i < length; i++)
            {
                for (int j = 0; j < width; j++)
                {
                    for (int k = 0; k < map[x + i, y + j].Length; k++)
                    {
                        yield return map[x + i, y + j][k];
                    }
                }
            }
        }
    }

1 Comment

Both this solution, and the LINQ solution work great, this one has a slight performance boost over the LINQ, which is why I am giving the answer to you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.