Changes Cascading down to children in a Tree structure ASP.NET MVC 3

跟風遠走 提交于 2020-01-16 07:56:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!