linq - How to get total count of children of a class containing Dictionary of same type? -
i have 'node' class follows:
public class node { public readonly idictionary<string, node> _nodes = new dictionary<string, node>(); public string path { get; set; } }
i want total child count of _nodes
of object of above class. there can level of depths. let suppose create object as:
node obj = new node();
after iterating, wish total no of node
s @ levels of depth. tried following not working:
foreach (var item in obj._nodes) { count += item.value._nodes.selectmany(list => list.value._nodes).distinct().count(); }
a typical solution problem create recursive method, this:
public class node { public readonly idictionary<string, node> _nodes = new dictionary<string, node>(); public int gettotalchildrencount() { return _nodes.values.sum(n => n.gettotalchildrencount() + 1); } }
+ 1
part used count node itself, apart number of children.
i've omitted call distinct
function. won't work, node doesn't have equals
, gethashcode
method overridden.
Comments
Post a Comment