c# - How to best traverse Children of Children's Children to an unknown depth? -
this question has answer here:
- how search hierarchical data linq 8 answers
imagine object properties:
class testobject { public string name { get; set; } public collection<testobject> children { get; set; } }
now initialize in jagged fashion:
var person1 = new testobject(){ name = "joe", children = new collection<testobject>(){ childcollection1 }; }; var person2 = new testobject(){ name = "mary", children = new collection<testobject>(){ childcollection2 }; };
where joe's childcollection 1 level deep, mary's children have children, have children.
i have attempted use selectmany no luck.
// works var joe = person1.children.selectmany(c => c.children).concat(person1.children); // not work - returns 1 level deep var mary = person2.children.selectmany(c => c.children).concat(person2.children);
what best way retrieve result containing every child, unknown depth?
you can write generic traverse method this:
public static ienumerable<t> traverse<t>(t root, func<t, ienumerable<t>> childselector) { var stack = new stack<t>(); stack.push(root); while (stack.any()) { var next = stack.pop(); yield return next; foreach (var child in childselector(next)) stack.push(child); } }
this general model that's useful traversing trees in general. note depth first search. if want breath first search use queue<t>
instead of stack<t>
.
Comments
Post a Comment