【发布时间】:2021-01-20 14:43:10
【问题描述】:
我在 C# 中有一个 Node 类,具有以下属性:
public class Node
{
public int Id {get;set;}
public int? ParentId {get;set;}
public string Label {get;set;}
}
我有一个TreeView 控件,它提供以下创建方法
一个新节点:
MyTreeView.CreateNode(key, label);
parent.Nodes.CreateNode(key, label);
如果我想添加一个新的子节点,我需要使用第二种方法,否则使用第一种。两者都返回TreeNode 类型的对象。
考虑到根节点具有ParentId = null,您将如何在 C# 中创建递归函数来填充树视图?
这是我到目前为止所做的:
// create a list of root nodes
var roots = myList.Where(x => x.ParentId == null);
// send the roots to a recursive func
foreach(var root in roots)
{
AddNode(null,root,myList);
}
这是我的递归函数:
private void AddNode(Node parent, Node current, IList<Node> items)
{
TreeNode treenode = null;
if(parent == null)
{
treenode = mytree.CreateNode(current.Id.ToString(), current.Label);
}else{
var parentnode = mytree.GetNode(parent.Id.ToString());
treenode = parentnode.Nodes.CreateNode(current.Id.ToString(), current.Label);
}
// call the recursion for the children
var children = items.Where(x => x.ParentId == current.Id);
foreach(var child in children)
{
AddNode(current, child, items);
}
}
【问题讨论】:
-
你需要添加C#标签。如果这是作业,您也应该添加作业标签。此外,您应该向我们展示您尝试过的代码示例。
-
好的,我会修改帖子,谢谢。
-
这个函数有什么问题?除了你不需要变量 treenode
-
这是错误的,因为我必须在一个电话中完成所有事情,我在这里做的是两个电话。我想用 LinQ 添加一个扩展,但我不太擅长。
-
你忘了提一些我觉得很重要的事情。您正在根据某种
IList生成您的树,您的列表中有什么?可以做出推断,但不能确定