如何使用LINQ从树中的所有节点获取List?

时间:2010-08-11 12:43:07

标签: c# .net linq

如何使用LINQ从树中的所有节点获取List?

我的课程是:

class Node
{
 public class Node()
 {
  Children = new List<Node>();
 }

 public List<Node> Children { get; set;}
}

class Tree
{
 public Tree()
 {
  Roots = new List<Node>();
 }

 List<Node> Roots { get; set;}
}

3 个答案:

答案 0 :(得分:3)

class Node
    {
    public Node()
    {
        Children = new List<Node>();
    }

    public IEnumerable<Node> GetSubTree()
    {
        return Children.SelectMany(c => c.GetSubTree()).Concat(new[] { this });
        //Post-order traversal
    }

    public List<Node> Children { get; set; }
}

class Tree
{
    public Tree()
    {
        Roots = new List<Node>();
    }

    public IEnumerable<Node> GetAllNodes()
    {
        return Roots.SelectMany(root => root.GetSubTree());
    }

    List<Node> Roots { get; set; }
}

树如何拥有多个根?这不是森林吗?

答案 1 :(得分:3)

var allNodes = yourTree.Roots.SelectMany(x => x.TraverseTree(y => y.Children));

// ...

public static class EnumerableExtensions
{
    public static IEnumerable<T> TraverseTree<T>(
        this T parentNode, Func<T, IEnumerable<T>> childNodesSelector)
    {
        yield return parentNode;

        IEnumerable<T> childNodes = childNodesSelector(parentNode);
        if (childNodes != null)
        {
            foreach (T childNode in
                childNodes.SelectMany(x => x.TraverseTree(childNodesSelector)))
            {
                yield return childNode;
            }
        }
    } 
}

答案 2 :(得分:1)

您可以通过添加traversal method或使用recursive LINQ with Y-combinator来完成此操作。我个人更喜欢第一种方法。