C# 如何使用递归将列表转换为树
我们有一个列表需要转换为树。 数据结构C# 如何使用递归将列表转换为树,c#,asp.net,C#,Asp.net,我们有一个列表需要转换为树。 数据结构 public class node { public string name { get; set; } public string Path { get; set; } public List<node> child { get; set; } } 结果需要转换为: "FileName":"a", "Path":null, "ChildNode":[{ "FileName":"b",
public class node
{
public string name { get; set; }
public string Path { get; set; }
public List<node> child { get; set; }
}
结果需要转换为:
"FileName":"a",
"Path":null,
"ChildNode":[{
"FileName":"b",
"Path":null,
"ChildNode":[{
"FileName":"2017.log",
"Path":"a\b\\财务\2017.log",
"ChildNode":null
publicstatictreenodegettreenode(DirectoryInfo d)
{
DirectoryInfo[]children=d.GetDirectories();
FileInfo[]files=d.GetFiles();
IEnumerable childNodes=从子对象中的子对象选择GetTreNode(子对象);
IEnumerable fileNodes=从文件中的文件选择新树节点(file.Name,file.Path,null);
返回新的TreeNode(d.Name,null,childNodes.Concat(fileNodes.ToList());//这里我们合并目录列表和文件列表
}
//复合材料
class TreeNode
{
string name;
string path;
List<TreeNode> children;
public TreeNode(string n, string p, List<TreeNode> cn)
{
this.name = n;
this.path = p;
this.children = cn;
}
}
类树节点
{
字符串名;
字符串路径;
列出儿童名单;
公共树节点(字符串n、字符串p、列表cn)
{
this.name=n;
this.path=p;
这个.儿童=cn;
}
}
不是免费的代码编写服务。您应该尝试自己编写代码。之后,如果你有问题,你可以张贴你已经尝试了一个明确的解释什么是不工作,并提供一个解决方案。我建议你读一个好的问题和答案。此外,一定要采取。和至少张贴正确的文本\财务 这不存在于var path=@“…”啊。。。不仅仅是一个树结构,它看起来是一个链表结构。。。每个父项都有0-1个子项。。。
public static TreeNode GetTreeNode(DirectoryInfo d)
{
DirectoryInfo[] children = d.GetDirectories();
FileInfo[] files = d.GetFiles();
IEnumerable<TreeNode> childNodes = from child in children select GetTreeNode(child);
IEnumerable<TreeNode> fileNodes = from file in files select new TreeNode(file.Name, file.Path, null);
return new TreeNode( d.Name, null, childNodes.Concat(fileNodes).ToList()); //Here we are merging directory list & File List
}
class TreeNode
{
string name;
string path;
List<TreeNode> children;
public TreeNode(string n, string p, List<TreeNode> cn)
{
this.name = n;
this.path = p;
this.children = cn;
}
}