I am working with a tree type structure that consists of a single 'root'TreeNodeDefinition record which can contain amongst other things a list of other TreeNodeDefinition classes, each of these can then contain a further List and so on and so forth.
I basically want to be able to traverse ALL nodes within the tree structure and check if a condition is met per node then that definition record is added to a list. I have come up with a method to do this but I cant help but think there is a much more efficient way of doing it:
List<ITreeNodeDefinition> treeNodeDefinitions = new List<ITreeNodeDefinition>();
treeNodeDefinitions = treeFactory.SearchNodesByRelationshipId(treeNodeDefinition, relationshipId, new List<ITreeNodeDefinition>());
where the first parameter is my Root node definition record, the second parameter is what I need to compare each node by and lastly I am passing in an Empty list that I want to populate each time a node matches my check. The method is as follows:
public List<ITreeNodeDefinition> SearchNodesByRelationshipId(ITreeNodeDefinition treeNodeDefinition, int? relationshipId, List<ITreeNodeDefinition> tndList)
{
if (treeNodeDefinition.RelationshipId == relationshipId)
{
tndList.Add(treeNodeDefinition);
}
if (treeNodeDefinition.Nodes.Count != 0)
{
foreach (ITreeNodeDefinition nodeDefinition in treeNodeDefinition.Nodes)
{
List<ITreeNodeDefinition> tempTable = this.SearchNodesByRelationshipId(nodeDefinition, relationshipId, tndList);
}
}
return tndList;
}
As you can see, the method is calling itself for each sub-node found in the treeNodeDefinition.Nodes list. This is returning to a tempTable that I never do anything with... This stinks of inefficiency to me. i was wondering if there is a more direct way of navigating this kind of structure... I sure I am just missing a trick.