using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 字典转树形结构
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, List<string>> FileDic = new Dictionary<string, List<string>>();
FileDic["CTree"] = new List<string> { "a.c", "b.c" };
FileDic["a.c"] = new List<string> { "1.h" };
FileDic["b.c"] = new List<string> { "11.h" };
FileDic["1.h"] = new List<string> { "2.h", "5.h", "7.h" };
FileDic["2.h"] = new List<string> { "3.h", "4.h" };
FileDic["3.h"] = new List<string>();
FileDic["4.h"] = new List<string>();
FileDic["5.h"] = new List<string> { "6.h" };
FileDic["6.h"] = new List<string>();
FileDic["7.h"] = new List<string> { "8.h", "9.h", "10.h" };
FileDic["8.h"] = new List<string>();
FileDic["9.h"] = new List<string>();
FileDic["10.h"] = new List<string>();
FileDic["11.h"] = new List<string> { "12.h" };
FileDic["12.h"] = new List<string> { "11.h" };
IncludeFileNode tree = new IncludeFileNode();
List<string> nodelist = new List<string>();
tree.Children = CreateChildNode(FileDic, "CTree", nodelist);
}
public static List<IncludeFileNode> CreateChildNode(Dictionary<string, List<string>> fileDic, string key, List<string> nodelist)
{
//childNode:子节点
List<IncludeFileNode> childNode = new List<IncludeFileNode>();
foreach (var value in fileDic[key])
{
nodelist.Add(value);
if (isLoopInclude(nodelist, fileDic, value))
{
break;
}
//nextNode:下个节点
IncludeFileNode nextNode = new IncludeFileNode();
nextNode.FileName = value;
//将当前节点的值作为获取下个节点函数的key变量
nextNode.Children = CreateChildNode(fileDic, value, nodelist);
childNode.Add(nextNode);
}
return childNode;
}
private static bool isLoopInclude(List<string> nodelist, Dictionary<string, List<string>> fileDic, string key)
{
bool loopInclude = false;
if (fileDic[key].Count == 0)
{
nodelist.Clear();
}
if ((from t in nodelist where t.Equals(key) select t).Count() == 2)
{
loopInclude = true;
}
return loopInclude;
}
}
class IncludeFileNode
{
public string FileName { get; set; }
public List<IncludeFileNode> Children { get; set; }
}
}