c# - Retrieve a list of tree paths -
i have tree , using code found here functionally traversing tree in c# paths in tree. thing is, code returns list of each path in tree. example, if have following tree:
a--- | ---b | ---c | ---d | ---e
the code return {a},{a,b},{a,c},{a,c,d},{a,c,e}
where need return branches i.e. {a,b},{a,c,d},{a,c,e}.
this doesn't have part of method above, long in end list branches , not every path.
what i'm trying figure out how filter ienumerable list above method have entries last element in each list has no children.
so in current code:
class node { public string name; public int parentid; public list<node> children; }
and in main code
list<node> listofnodes = gettreenodes(); node rootnode = listofnodes.where(n => n.parentid == 0).firstordefault(); // below paths var have every path instead of branches var paths = computepaths(rootnode, n=>n.children);
using code linked answer:
static ienumerable<ienumerable<t>> computepaths<t>(t root, func<t, ienumerable<t>> children) { yield return new[] { root }; foreach (var child in children(root)) foreach (var childpath in computepaths(child, children)) yield return new[] { root }.concat(childpath); }
hope makes sense. appreciated.
this works:
static ienumerable<ienumerable<t>> computepaths<t>(t root, func<t, ienumerable<t>> children) { var children = children(root); if (children != null && children.any()) { foreach (var child in children) foreach (var childpath in computepaths(child, children)) yield return new[] { root }.concat(childpath); } else { yield return new[] { root }; } }
if node leaf node (without children), return itself. otherwise, return path of children.
Comments
Post a Comment