bdtrfs
bdtrfs

Reputation: 13

Iterate through nested list with many layers

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.

Upvotes: 1

Views: 4343

Answers (1)

Scott Perham
Scott Perham

Reputation: 2470

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!

Upvotes: 6

Related Questions