Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Tree concept not working with c# iterators

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);

>Solution :

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
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading