How can I get a List from all nodes in a tree using LINQ?
How can I get a List from all nodes in a tree using LINQ?
My c开发者_开发技巧lasses are:
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;}
}
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; }
}
How can a tree have more than one root though? Isn't this a forest?
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;
}
}
}
}
You can do this by either adding a traversal method, or by using recursive LINQ with Y-combinator. I personally prefer first approach.
精彩评论