Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

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);
    }
}
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #deeply #related #children
ADD COMMENT
Topic
Name
7+2 =