0

In C#, if I have a CollectionBase of type T, and each item in the CollectionBase can have a child CollectionBase of the same type T, how can I get a list of all type T objects without using a recursive function?

Does LINQ have a feature to do this?

Thanks in advance.

Simon
  • 7,991
  • 21
  • 83
  • 163

1 Answers1

0

Wes Dyer wrote actually a nice topic on this, have a look.

As for your case I think you would need an iterator, probably something like this:

public static IEnumerable<T> Flatten<T>(this IEnumerable<T> e, Func<T,IEnumerable<T>> f) 
{
   return e.SelectMany(c => f(c).Flatten(f)).Concat(e);
}

This is answer is taken from here.

EDIT: I just remember that you can also traverse the tree.

public static IEnumerable<T> Traverse<T>(T item, Func<T, IEnumerable<T>> childSelector)
{
    var stack = new Stack<T>();
    stack.Push(item);
    while (stack.Any())
    {
        var next = stack.Pop();
        yield return next;
        foreach (var child in childSelector(next))
        stack.Push(child);
    }
}
Community
  • 1
  • 1
Mō Iđɍɨɇƶ
  • 331
  • 1
  • 8