NetUser101 NetUser101 - 1 month ago 12
C# Question

Adding an item to nested lists

I have the following class:

public class Parent
{
public int Id { get; set; }
public string Name { get; set; }
public List<Parent> Children { get; set; }
}


From a parent I can have multiple Children, and each of those children can have more children, etc.

Now my aim is to populate this object/list in a hierarchical form. I start with the top and slowly add onto it so that it branches out, however I have an issue. How can I find and add an item to a particular child?

Edit:
Several methods have been provided to find that node and add to that node. However this issue remains:

Consider this: I have a Parent which already has a few children. I will use the Find method to find one of these children and this method with return a Child. Now I need to add a new child to that child in my parent. When I used your code, it added the Child to the Child that the method Find returned, however it did not affect my original Parent. The list of children of that Parent was still 0 when I wanted it to have the child that I newly added.

Drawn out example: This is the list that I already have

- Mary
- Peter
- Jake
- Luke


In this example, Mary has two children, Peter and Luke. Peter has a child, Jake. My aim is to find Jake and a add a child to Jake. I can do this by using a recursive search and that will successfully return Jake. I can add a child (John) to Jake and that will leave me with this:

- Jake
- John


However I need to modify the original parent so that I will have:

- Mary
- Peter
- Jake
- John
- Luke

Answer

you need to recursivly search for your node in the tree:

public static Parent FindNode(int id, Parent current)
{
    if (current.Id == id)
    {
        return current;
    }

    foreach (var child in current.Children)
    {
        var ret = FindNode(id, child);
        if (ret != null)
        {
            return ret;
        }
    }

    return null;
}

usage example (root represents the root node of your tree):

var node = FindNode(myId, root, root);
if (node != null)
{
    node.Children.Add(newChildren);
}
Comments