-2

I have class which is Item below

public class Item 
{
  public int id { get; set; }
  public readonly List<Item> Children = new List<Item>(); 
}

and i have List of this class.

List<WorkItem> treeList = new List<WorkItem>();

I added Children to Item recursively thats its means, Item can have "n" Children and "n" Children can have "n" Children too.

  • Item
    • Children
      • Children
        • .......
        • ..........
    • Children
  • Item

How can i do foreach in Items all Children notwithstanding know depth of Children.

Thanks

Pedro
  • 31
  • 5
  • 5
    have you... ***tried anything***? you've already mentioned the keyword to solve your problem, by the way - "recursion". and [here](https://learn.microsoft.com/en-gb/dotnet/csharp/language-reference/keywords/yield) is another pointer to help you solve your problem. – Franz Gleichmann Aug 18 '20 at 19:13
  • *"How can i do foreach"* - You don't. Traversing a tree of unknown depth is a job for recursion, not iteration. – David Aug 18 '20 at 19:14
  • 1
    To be fair, everything you can do with recursion, you can do iteratively. Some things are simpler with one, some with the other. In this case, recursion would be a better fit, yes. – insane_developer Aug 18 '20 at 19:18
  • Since you want to use `foreach` you need to have iterator that walks the tree - which we have plenty of questions for - https://www.bing.com/search?q=c%23+yield+return+recursive+tree+site%3astackoverflow.com, I picked couple duplicates showing how to construct that enumerator to use with `foreach`. – Alexei Levenkov Aug 18 '20 at 19:44

1 Answers1

1

For each item in the collection, you process the item and then you recursively do the same thing for it's children collection:

public static void ProcessAllItemsAndChildren(List<Item> items)
{
    if (items == null) return;

    foreach (var item in items)
    {
        processItem(item);
        processAllChildren(item.Children);
    }
}

public static void processItem(Item item)
{
    // Here's where we actually do something with an individual item
}
Rufus L
  • 36,127
  • 5
  • 30
  • 43