Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hierarchical structure iteration and LINQ

Assume that we have class

public class RMenuItem
{
    public List<RMenuItem> ChildrenItems { get; }
    public decimal OperationID { get; }
    public string Name { get; }
}

as you can see - each menuitem could have children items - as usual in menu. My task is to iterate through each items of this list and apply some action to it. Classical decision is to write recursive iteration. But I'm interesting if LINQ could make my task easier? For example, I suppose that we can write query that can get flat list of objects, which i can iterate simply with foreach. But my attempts in this way weren't successful yet. So any help appreciated!

like image 470
Andrey Khataev Avatar asked Dec 07 '25 10:12

Andrey Khataev


1 Answers

It's possible:

    public void PrintAllNames(RMenuItem rootItem)
    {
        Action<RMenuItem> print = null;
        print = m =>
            {
                Console.WriteLine(m.Name);
                m.ChildrenItems.ForEach(print);
            };
        print(rootItem);
    }

Notice how it's necessary to declare print so that print can use itself. This is directly comparable to a recursive method, which I'd rather use:

    public void PrintAllNames(RMenuItem rootItem)
    {
        Console.WriteLine(rootItem.Name);
        rootItem.ChildrenItems.ForEach(PrintAllNames);
    }

(although for a more complex situation, maybe the functional solution would make the most sense)

like image 149
Rob Fonseca-Ensor Avatar answered Dec 12 '25 18:12

Rob Fonseca-Ensor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!