我怎样才能获得使用LINQ在树中的所有节点的列表? [英] How can I get a List from all nodes in a tree using LINQ?
本文介绍了我怎样才能获得使用LINQ在树中的所有节点的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我怎样才能得到一个列表,使用LINQ在树中的所有节点?
我的类:
类节点
{
公共类节点()
{
儿童=新的名单,其中,节点>();
}
公开名单<节点>儿童{获得;组;}
}
类树
{
公共树()
{
根=新的名单,其中,节点>();
}
名单<节点>根{获得;组;}
}
解决方案
类节点
{
公共节点()
{
儿童=新的名单,其中,节点>();
}
公开的IEnumerable<节点> GetSubTree()
{
返回Children.SelectMany(C => c.GetSubTree())。CONCAT(新[] {此});
//后序遍历
}
公开名单<节点>儿童{获得;组; }
}
类树
{
公共树()
{
根=新的名单,其中,节点>();
}
公开的IEnumerable<节点> GetAllNodes()
{
返回Roots.SelectMany(根=> root.GetSubTree());
}
名单<节点>根{获得;组; }
}
如何才能一棵树有一个以上的根关系吗?这不是一个森林吗?
How can I get a List from all nodes in a tree using LINQ?
My classes 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?
这篇关于我怎样才能获得使用LINQ在树中的所有节点的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文