📜  c# 深度相关的孩子 - C# 代码示例

📅  最后修改于: 2022-03-11 14:48:41.997000             🧑  作者: Mango

代码示例1
// 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 Traverse(
      T root, 
    Func> childSelector)
{
    var stack = new Stack();
    stack.Push(root);

    while (stack.Any())
    {
        var next = stack.Pop();
        yield return next;
        foreach (var child in childSelector(next))
            stack.Push(child);
    }
}