Click here to Skip to main content
15,886,067 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a kind of own tree structure.

As you can see, this can have any depth. However, I have problems going through this structure now. With foreach loops, I can always search only one list, but not the children lists. How would you do that?

What I have tried:

public class MyClass
{
   public string Name{ get; set; }
   public List<MyClass> Children { get; set; }
}
Posted
Updated 27-Jun-18 22:44pm
v3

This is an English language site, and we only accept and answer questions in that language. In future, please use Google Translate to help post your question - it does a pretty good job!

The easiest way to process lists of lists where the depth is unknown is to use recursion:
C#
public void Process(MyClass mc)
   {
   ... Process instance mc ...
   if (mc.Children != null)
      {
      foreach (MyClass child in mc.Children)
         {
         Process(child);
         }
      }
   }
Pass it the "main item" and it will perform the same operation on each child, regardless of the depth.
 
Share this answer
 
Given a search() function :
C#
public MyClass search(Myclass node)
{
    foreach(var c in node.Children)
    {
       // search code here if found
       // return c

       // else go down
       var ret = search(c);
       if(ret != null)
          return ret;
    }
    return null;
}
You can switch the blocks to do depth first search.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900