I'm learning c# iterators and I'm trying to make them work in this kind of tree like structure but unfortunately all I can get is to enumerate the root and their direct children.
public class Node : IEnumerable<Node>
{
private Node Parent = null;
private List<Node> Children = new List<Node>();
public string Name { get; private set; };
public Node(string name)
{
Name = name;
}
public Node AddChild(Node child)
{
Children.Add(child);
child.Parent = this;
return child;
}
public IEnumerator<Node> GetEnumerator()
{
yield return this;
foreach (var x in Children)
yield return x;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
I've tried to go recursive with a static method but IEnumerator doesn't allow it as it has to return T. Could anyone what's wrong with this approach? Thanks in advance.
Usage example:
Node root = new Node("html");
root.AddChild(new Node("body")).AddChild(new Node("i")).AddChild(new Node("b"));
foreach(var m in root)
Console.WriteLine(m.Name);
you have one foreach missing
public IEnumerator<Node> GetEnumerator()
{
yield return this; // returns current item
foreach (var x in Children) // iterates over children list
foreach (var c in x) // iterates over child enumerator
yield return c; // returns child and grandchildren
}