mynode mytree=new mynode()
{
id = "1",
text = "note1",
children = new List<mynode>()
{
new mynode(){id = "1-1" , text = "1-note1" ,
children = new List<mynode>()
{
new mynode(){id = "1-1-1" ,text = "1-1-note1"},
new mynode(){id = "1-1-2" ,text = "1-1-note2"},
}},
new mynode(){id = "1-2" , text = "1-note2" ,
children = new List<mynode>()
{
new mynode(){id = "1-2-1" ,text = "1-2-note1"},
new mynode(){id = "1-2-2" ,text = "1-2-note2"},
}},
}
};
now you want to find id "1-1-2"
var row = GetTree(mytree, "1-1-2");
if (row != null)
{
Response.Write(row.id + " " + row.text );
}
and your method
public mynode GetTree(mynode node, string id)
{
if (node.id == id)
return node;
else
{
if (node.children != null)
{
foreach (var mynode in node.children)
{
var result= GetTree(mynode, id);
if (result != null)
return result;
}
}
}
return null;
}
Member
9 Points
26 Posts
Find a node in Tree Structure
Jun 06, 2018 04:03 AM|Shan kHAN|LINK
Hi All,
i have a tree structure based on following class
now in order to update or add child to a node, first i would need to find that node based on node id in my tree object
how i can find a specific node based on id, as there could be children and their children on many levels, like a tree
for normal list of objects i used the following
int i = mytree .FindIndex(
delegate (mynode temp)
{
return temp.id.Equals(given_id);
});
but here each object in the list further contains children
,
please give me any solution
Thanks
Star
8119 Points
2778 Posts
Re: Find a node in Tree Structure
Jun 06, 2018 07:18 AM|vahid bakkhi|LINK
hi
you have to write a recursive method below like :
for example your tree is below like :
id text
1 note1
------------->1-1 1-note1
--------------------------------->1-1-1 1-1-note1
--------------------------------->1-1-2 1-1-note2
------------->1-2 1-note2
--------------------------------->1-2-1 1-2-note1
--------------------------------->1-2-2 1-2-note2
now you want to find id "1-1-2"
and your method
I hope it can be helpful
Please MARK AS ANSWER if suggestion helps.
Member
9 Points
26 Posts
Re: Find a node in Tree Structure
Jun 06, 2018 03:12 PM|Shan kHAN|LINK
Thanks Vahid bakkahi,
it worked for me, i really appreciate the way you given the solution in complete detail with the code