1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading.Tasks;
6
7 namespace 字典转树形结构
8 {
9 class Program
10 {
11 static void Main(string[] args)
12 {
13 Dictionary<string, List<string>> FileDic = new Dictionary<string, List<string>>();
14 FileDic["CTree"] = new List<string> { "a.c", "b.c" };
15 FileDic["a.c"] = new List<string> { "1.h" };
16 FileDic["b.c"] = new List<string> { "11.h" };
17 FileDic["1.h"] = new List<string> { "2.h", "5.h", "7.h" };
18 FileDic["2.h"] = new List<string> { "3.h", "4.h" };
19 FileDic["3.h"] = new List<string>();
20 FileDic["4.h"] = new List<string>();
21 FileDic["5.h"] = new List<string> { "6.h" };
22 FileDic["6.h"] = new List<string>();
23 FileDic["7.h"] = new List<string> { "8.h", "9.h", "10.h" };
24 FileDic["8.h"] = new List<string>();
25 FileDic["9.h"] = new List<string>();
26 FileDic["10.h"] = new List<string>();
27 FileDic["11.h"] = new List<string> { "12.h" };
28 FileDic["12.h"] = new List<string> { "11.h" };
29
30 IncludeFileNode tree = new IncludeFileNode();
31 List<string> nodelist = new List<string>();
32 tree.Children = CreateChildNode(FileDic, "CTree", nodelist);
33 }
34
35 public static List<IncludeFileNode> CreateChildNode(Dictionary<string, List<string>> fileDic, string key, List<string> nodelist)
36 {
37 //childNode:子节点
38 List<IncludeFileNode> childNode = new List<IncludeFileNode>();
39 foreach (var value in fileDic[key])
40 {
41 nodelist.Add(value);
42 if (isLoopInclude(nodelist, fileDic, value))
43 {
44 break;
45 }
46 //nextNode:下个节点
47 IncludeFileNode nextNode = new IncludeFileNode();
48 nextNode.FileName = value;
49 //将当前节点的值作为获取下个节点函数的key变量
50 nextNode.Children = CreateChildNode(fileDic, value, nodelist);
51 childNode.Add(nextNode);
52 }
53 return childNode;
54 }
55
56 private static bool isLoopInclude(List<string> nodelist, Dictionary<string, List<string>> fileDic, string key)
57 {
58 bool loopInclude = false;
59 if (fileDic[key].Count == 0)
60 {
61 nodelist.Clear();
62 }
63 if ((from t in nodelist where t.Equals(key) select t).Count() == 2)
64 {
65 loopInclude = true;
66 }
67 return loopInclude;
68 }
69 }
70
71 class IncludeFileNode
72 {
73 public string FileName { get; set; }
74 public List<IncludeFileNode> Children { get; set; }
75 }
76 }
原创文章,作者:carmelaweatherly,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/273819.html