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.

1
  • A shame that the Linq solution is so horribly inefficient... I would recommend against using it (as did Eric Lippert!) Commented Feb 14, 2017 at 11:34

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.