How to best traverse Children of Children's Children to an unknown depth?
c#, linq
Solution
You can write a generic traverse method like this:
public static IEnumerable<T> Traverse<T>(T root,
Func<T, IEnumerable<T>> childSelector)
{
var stack = new Stack<T>();
stack.Push(root);
while (stack.Any())
{
var next = stack.Pop();
yield return next;
foreach (var child in childSelector(next))
stack.Push(child);
}
}
This is a general model that's useful for traversing trees in general. Note that this will do a depth first search. If you want a breath first search you would use a `Queue<T>` instead of a `Stack<T>`.
Problem
Imagine an object with the properties: ``` class TestObject { public string Name { get; set; } public Collection<TestObject> Children { get; set; } } ``` Now initialize some in a jagged fashion: ``` var person1 = new TestObject(){ Name = "Joe", Children = new Collection<TestObject>(){ childCollection1 }; }; var person2 = new TestObject(){ Name = "Mary", Children = new Collection<TestObject>(){ childCollection2 }; }; ``` Where Joe's childCollection is only one level deep, but Mary's children have children, who also have children. I have attempted to use SelectMany with no luck. ``` // Works var joe = person1.Children.SelectMany(c => c.Children).Concat(person1.Children); // Does not work - only returns 1 level deep var mary = person2.Children.SelectMany(c => c.Children).Concat(person2.Children); ``` What is the best way to retrieve a result containing every child, to an unknown depth?