I have a class like:
class Spline
int ChildrenCount;
Spline GetChild (int index)
class SplineCollection : IEnumerable<Spline>
Spline Master
Is it possible to write a recursive IEnumerable for the SplineCollection where it will return all the children one by one?
EDIT: So Master is the root Box, and the hierarchy of its children can be any depth.
EDIT: By using the name Box, I think I confused some people. It's meant to be a geometric object, not a container. So changing it to Spline.
I would go with manually maintaining a stack instead of relying on the call stack here. The reason is because a new IEnumerable<Spline>
would have to be created for each Spline
visited if you used the call stack by recursively calling the method that gets the descendants. That would be inefficient. You can significantly improve the traversal by using your own stack.
public IEnumerable<Spline> Descendants
{
get
{
// This performs a simple iterative preorder traversal.
var stack = new Stack<Spline>(new Spline[] { this });
while (stack.Count > 0)
{
Spline current = stack.Pop();
yield return current;
for (int i = current.ChildrenCount - 1; i >= 0; i--)
{
stack.Push(current.GetChild(i));
}
}
}
}
This will do a depth-first traversal of the Box
'tree'. You can then just call this method on the Master
box to return all the recursive children.
public class Box
{
// ...
public IEnumerable<Box> GetBoxes()
{
yield return this;
for (int i=0; i<box.ChildrenCount; i++)
{
foreach (Box child in box.GetChild(i).GetBoxes())
{
yield return child;
}
}
}
}
Yep - see this section for Recursive Iterations using C# iterators.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With