0

I have a list of parent objects that have children which I send to the view. Their children can have children and so on and so forth. Is there a simpler way to iterate through my objects and generate a <ul> list with sub-lists based on my setup for infinite children->grandchildren->great grandchildren, etc?

Here's what I have:

<ul>
    @foreach (var item in Model)
    {       
        <li>
            @item.Name
            @if (item.Children != null)
            {
            <ul>
                @foreach (var child in item.Children)
                {
                <li>
                    @child.Name
                </li>

                    if (child.Children != null)
                    {
                    <li style="list-style:none;">
                        <ul>
                            @foreach (var grandchild in child.Children)
                            {
                            <li>
                                @grandchild.Name
                                @if (grandchild.Children != null)
                                {
                                    <ul>
                                        @foreach(var greatgrandchild in grandchild.Children)
                                        {
                                            <li>
                                                @greatgrandchild.Name
                                            </li>
                                        }
                                    </ul> 
                                }
                            </li>
                            }
                        </ul>
                    </li>
                    }
                }
            </ul>
            }
        </li>
        }
</ul>
justiceorjustus
  • 2,017
  • 1
  • 19
  • 42

1 Answers1

1

You could do it recursively. something like

@Action<childBearing> recursive = (children) => {
    <ul>
        @foreach(var child in children){
           <li>
                @if(child.children != null){
                    recursive(child);
                }
                @child.name
            </li>
         }
    </ul>
}

where childBearing is whatever type your object is. This assumes that each generation is of the same type, however. I haven't tested it but it might be a good starting point.

edit: You might not want to make it an anonymous delegate, if you do you might want to take a look at this Can an anonymous method in C# call itself?

Reese De Wind
  • 206
  • 2
  • 5