3

I'm having a nested class :

    class Item
    {
        public Int32 Id { get; set; }
        public Int32 Pid { get; set; }
        public String Name { get; set; }
        public IEnumerable<Item> Children { get; set; }

    }

Now I want to flatten this so I can get the name of all Items and their childeren.

Problem here is that I don't know how many levels deep this goes.

I had a look at :

How to flatten nested objects with linq expression

This is great if you know how many levels you have, which I don't.

So :

        var r = from b in items
                from c in b.Children
                from d in c.Children
                ...
                select new { b.Name, c = c.Name, d = d.Name ... };

does pretty much what I need, but I don't know how many levels deep I need to go, also if one item does not have a child it doesn't return anything.

I would need some recursive routine on this I guess, but I can't seem to find it. I looked at IEnumerable but I don't really understand this yet :)

So any help would be very much appriciated.

Community
  • 1
  • 1
MDV
  • 31
  • 1
  • 2

1 Answers1

3

You are right, you need recursion:

public IEnumerable<Item> GetAllChildren(Item item)
{
    return item.Children.Concat(item.Children.SelectMany(GetAllChildren));
}

To get all names you can project the result:

var allDescendantNames = GetAllChildren(item).Select(child => child.Name).ToList();
René Vogt
  • 43,056
  • 14
  • 77
  • 99