Reputation: 3278
I have an object Node with child Nodes. I would like to read all the Nodes & child nodes and display them into an asp.net dropdown list control.
The node is of type :
Microsoft.TeamFoundataion.WorkItemTracking.Client.Node
The Class Node looks like this :
public class Node
{
public string Name { get; set; }
public string Path { get; set; }
}
Each Node has many child nodes & the child nodes have more child nodes and so on....
I have code written to fetch the node & first level of child node. I cannot think how I can recursively read all the nodes ??
Dictionary<string,string> ParentN = new Dictionary<string,string>();
Dictionary<string, string> childN = new Dictionary<string, string>();
foreach (Node area in Proj.Nodes)
{
ParentN.Add(area.Name, area.Path);
Console.WriteLine(area.Path);
foreach (Node item in area.ChildNodes)
{
childN.Add(item.Name, item.Path);
Console.WriteLine(item.Path);
}
}
Upvotes: 1
Views: 4495
Reputation: 12334
You need a recursive function for that. Children can be parents too. If a child has no children beneath it, then we don't add it to the parents dict.
void GetNode(Node parent)
{
if (parent.ChildNodes.Any())
{
ParentN.Add(parent.Name, parent.Path);
foreach(child in parent.ChildNodes)
{
childN.Add(child.Name, child.Path);
GetNode(child);
}
}
Console.WriteLine(parent.Name);
}
Upvotes: 4
Reputation: 8824
The class Node you posted does not contain child nodes. I'll assume you meant:
public class Node
{
public string Name { get; set; }
public string Path {get; set;}
IList<Node> ChildNodes { get; set; }
}
You could do it as:
static class NodeExtensions
{
public static IEnumerable<Node> ReadChildNodes(this Node node)
{
foreach(Node childNode in node.ChildNodes){
if(childNode.ChildNodes != null && childNode.ChildNodes.Any()){
foreach(Node grandChildren in childNode.ReadChildNodes())
yield return grandChildren;
}
yield return childNode;
}
}
}
Probably this code can be improved, but it works, I guess...
Upvotes: 2