1

Consider the scenario where you have a collection, and inside that collection are particular objects. Those objects also hold a collection, and inside those collections are more of the same objects. It's a nested collection with many layers.

List<WorkItemClassificationNode> items;
List<WorkItemClassificationNode> subItems = items.Children;
List<WorkItemClassificationNode> subSubItems = subItems.Children;
// etc

I just want a method to iterate through each of those layers so the same logic is applied to each item, but I can't think of a straightforward way of doing this without writing loads of nested loops.

Sunil
  • 3,404
  • 10
  • 23
  • 31
bdtrfs
  • 13
  • 1
  • 3
  • what you are looking for is called [Depth-first search](https://en.wikipedia.org/wiki/Depth-first_search) or [Breadth-first search](https://en.wikipedia.org/wiki/Breadth-first_search). Choose one , they are very helpfull – Mong Zhu Jan 30 '18 at 11:49

1 Answers1

6

You should look into writing a recursive method. (There is lots of information on the Internet about it)

Essentially, a recursive method is a method that calls itself.

void DoThing(WorkItemClassificationNode node)
{
    if (node == null)
        return;

    //Do something with node

    if (node.Children == null)
        return;

    foreach(var child in node.Children)
        DoThing(child);
}

Just be aware of the ever growing stack!

Scott Perham
  • 2,410
  • 1
  • 10
  • 20
  • This is by no means production code! :P Yes, perform null checks, yes, check the criteria for continuing down the recursive rabbit hole... – Scott Perham Jan 30 '18 at 11:52
  • @MongZhu The function will _always_ end after all children are processed. There is nothing preventing that. From the moment a node no longer has children, it'll just return to the previous level. The only initial condition for this to work is that child nodes _never_ link back to a parent, and if needed this can be checked with some kind of checklist of processed items passed to the function by reference. – Nyerguds Jan 30 '18 at 12:07
  • @MongZhu Scott Perham addressed that in his first response to you. It's the comment saying "This is by no means production code! Yes, perform null checks". But that depends on how the children are implemented; it's entirely possible the class always initializes the `Children` as an empty list. – Nyerguds Jan 30 '18 at 12:15
  • 1
    It won't call the recursive method if the list is empty... foreach creates an enumerator for which `MoveNext()` would return false if there are no items. The only issue here is the potential for null nodes and children (which I have now addressed) – Scott Perham Jan 30 '18 at 12:17
  • Thanks, that's what I was looking for – bdtrfs Jan 31 '18 at 16:53