dscythe
dscythe

Reputation: 71

Remove list from the recursive function if it is empty

Here is a sample code from C#(.cs)

private List<Menu> GetMenuTree(List<Menu> list, int? idparent)
{
    return list.Where(x => x.IDParent == idparent).Select(x => new Menu()
    {
        ID = x.ID,
        IDParent = x.IDParent,
        text = x.text,
        List = GetMenuTree(list, x.ID)
    }).ToList();
}

In the most child of the node it gives me (>) because the List is empty.

enter image description here

Here is the result JSON

{"ID":1,"IDParent":null,"text":"Furniture",
      "List":
           [{"ID":2,"IDParent":1,"text":"Table","List":[]},
            {"ID":3,"IDParent":1,"text":"Chairs","List":[]}]
}

Where List[] is empty. How to remove this if its in the most child of the node?

Upvotes: 0

Views: 157

Answers (1)

Ron Beyer
Ron Beyer

Reputation: 11273

I would add another function that determines if there are children or not:

private List<Menu> GetMenuTree(List<Menu> list, int? idparent)
{
    return list.Where(x => x.IDParent == idparent).Select(x => new Menu()
    {
        ID = x.ID,
        IDParent = x.IDParent,
        text= x.text,
        List = HasChildren(list, x.ID) ? GetMenuTree(list, x.ID) : null
    }).ToList();
}

public bool HasChildren(List<Menu> list, int? idparent)
{
    return list.Where(x => x.IDParent == idparent).FirstOrDefault() != null;
}

Or you could "in-line" that in the GetMenuTree function, but I think the readability this way is better.

Upvotes: 1

Related Questions