p__d p__d - 1 year ago 104
C# Question

Passing parent node in recursion

Is there any way to pass object (or reference) to a function, when that object is under 'construction' in recursion? I want to hold my parent node in his child.

Calling place in some method:

NavigationTreeNode node = FindNode(Resources.ShellView_TreeNodeBusinessRules);
var tmpList = LoadNodes(xDoc.Descendants("root").Elements("tab"), node);

And this is recursion:

private List<NavigationTreeNode> LoadNodes(IEnumerable<XElement> nodes, NavigationTreeNode parentNode)
return nodes.Select(x =>
new NavigationTreeNode(x.Attribute("display-name").Value, parentNode)
TabName = x.Attribute("tab-name").Value,
// Here I want to send object that is now under
// construction, or maybe reference
ChildNodes = LoadNodes(x.Elements("tab"), /* ?? */)

Answer Source

You can add the {} to specify the scope of the lambda expression and then you can save your new object to a variable, set its property and then return it:

return nodes.Select(x => 
    var obj = new NavigationTreeNode(x.Attribute("display-name").Value, parentNode)
        TabName = x.Attribute("tab-name").Value
    obj.ChildNodes = LoadNodes(x.Elements("tab"), obj);
    return obj;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download