Answers for "c# deeply related children"

C#
0

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);
    }
}
Posted by: Guest on November-08-2020

C# Answers by Framework

Browse Popular Code Answers by Language