Home > Net >  How to recursively check if the entity has a collection of children of that same entity?
How to recursively check if the entity has a collection of children of that same entity?

Time:10-01

So what I have is a node, which means a line of text. Here's the code:

public class Node : BaseEntity
{
    public string Name { get; set; }
    public int Position { get; set; }
    public Guid? ParentId { get; set; }
    public virtual Node Parent { get; set; }
    public virtual ICollection<Node> Children { get; set; }
}

This is how the should look:

A. Blabla
   A.1 Meetings
       A.1.1 Standup
   A.2 Documents
       A.2.1 Wages
             A.2.1.1 Management
             A.2.1.1 Workers
B. Whatever
 ....

So each node will have it's name, a position (A1, A2, etc...), it's parent if it has one (except the top most nodes for example A & B), and if it has children (for example A has children A1, A2, etc...)

How can I recursively check if a Node has Children, then foreach those children => if any of those children have children, etc...

Even if it's 7 layers deep for example...

CodePudding user response:

As far as I can understand, you basically have a tree structure there.

You already have the children information on a node, so you can check this post on how to iterate through them.

You can use this code to pass through your tree starting from a parent.

 public static void ProcessChildren(Node parent)
    {
        Console.WriteLine(parent.Position  " "  parent.Name);
        foreach (Node node in parent.Children)
        {
            ProcessChildren(node);
        }
    }
  • Related