Hierarchical structure iteration and LINQ

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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!

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)

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/1951713/hierarchical-structure-iteration-and-linq

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils