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

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

我的课程是:

class Node { public class Node() { Children = new List(); } public List Children { get; set;} } class Tree { public Tree() { Roots = new List(); } List Roots { get; set;} } 

 class Node { public Node() { Children = new List(); } public IEnumerable GetSubTree() { return Children.SelectMany(c => c.GetSubTree()).Concat(new[] { this }); //Post-order traversal } public List Children { get; set; } } class Tree { public Tree() { Roots = new List(); } public IEnumerable GetAllNodes() { return Roots.SelectMany(root => root.GetSubTree()); } List Roots { get; set; } } 

一棵树怎么能有多个根呢? 这不是森林吗?

 var allNodes = yourTree.Roots.SelectMany(x => x.TraverseTree(y => y.Children)); // ... public static class EnumerableExtensions { public static IEnumerable TraverseTree( this T parentNode, Func> childNodesSelector) { yield return parentNode; IEnumerable childNodes = childNodesSelector(parentNode); if (childNodes != null) { foreach (T childNode in childNodes.SelectMany(x => x.TraverseTree(childNodesSelector))) { yield return childNode; } } } } 

您可以通过添加遍历方法或使用带有Y-combinator的递归LINQ来完成此操作。 我个人更喜欢第一种方法。