c# deeply related children code example
Example: c# deeply related children
// Usage:
var relativeChildren = Traverse(myListOfRelativeChildren, item => item.Children);
relativeChildren.ToList().ForEach((child) =>
{
// this way you can even get the properties of child objects
Console.WriteLine(child.Id);
});
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);
}
}