问题
This is for an ASP.NET MVC 3 application and deals with updating children nodes in a tree structure. The user is allowed to make changes to any part of a node in the tree. Once the user has made a change, (i.e. to a Status field) that change will have to be cascaded down to all the children. The issue is there are an arbitrary amount of children and their children have an arbitrary number on children and so on. How would I go about doing this?
Thanks anyone who can help!
EDIT
I would like for this structure to repeat itself until there are no more children left
if (item.child.Count > 0) //Level 1
{
foreach (var item1 in item.child)
{
//Logic to update each entity
if (item1.child.Count > 0) //Level 2
{
foreach (var item2 in item1.child)
{
//Logic to update each entity
if (item2.child.Count > 0) //Level 3
{
foreach(var item3 in item2.child)
.
.
.
Is there an elegant way of doing this, or is it just some form of hardcoding this in for a "best guess" number or levels?
回答1:
You need to write a recursive method:
void ProcessChildren (Item item)
{
// Logic to update 'this' child item
foreach (var child in item.child)
{
ProcessChildren (child);
}
}
ProcessChildren (rootItem);
回答2:
thank you very much smith ...
im using collection of items to iterate over so below code is working for me .......
void ProcessChildren(ICollection<Item> items)
{
foreach (var child in items)
{
if(child.Count != 0)
ProcessChildren(child.ChildCategories);
}
}
ProcessChildren (rootItems);
来源:https://stackoverflow.com/questions/7277316/changes-cascading-down-to-children-in-a-tree-structure-asp-net-mvc-3