使用c#递归地构建具有父子关系的树

我有一个列表,我想转换为树结构。 如何将其转换为树形结构?

我通过递归检查父子关系C# thread查看了构建树类型列表,但由于我的类中的键是字符串,我不能使用该解决方案。 请帮忙

internal class Program { private static void Main(string[] args) { List nodeList = new List(); node n = new node("A", "A1", null, 1); nodeList.Add(n); n = new node("B", "A2", "A1", 2); nodeList.Add(n); n = new node("C", "A3", "A1", 2); nodeList.Add(n); n = new node("D", "A4", "A1", 2); nodeList.Add(n); n = new node("E", "A5", "A2", 3); nodeList.Add(n); n = new node("F", "A6", "A5", 4); nodeList.Add(n); n = new node("G", "A7", "A3", 3); nodeList.Add(n); n = new node("H", "A8", "A4", 3); nodeList.Add(n); n = new node("I", "A9", "A4", 3); nodeList.Add(n); n = new node("J", "A10", "A4", 3); nodeList.Add(n); n = new node("K", "A11", "A10", 4); nodeList.Add(n); n = new node("L", "A12", "A10", 4); nodeList.Add(n); n = new node("M", "A13", "A12", 5); nodeList.Add(n); n = new node("N", "A14", "A12", 5); nodeList.Add(n); n = new node("O", "A15", "A10", 4); nodeList.Add(n); n = new node("P", "A16", null, 1); nodeList.Add(n); n = new node("Q", "A17", "A16", 2); nodeList.Add(n); } } public class node { public string name { get; set; } public string key { get; set; } public string parentKey { get; set; } public int level { get; set; } public List Children { get; set; } public node(string Name, string Key, string PK, int Level) { name = Name; key = Key; parentKey = PK; level = Level; } } 

将父ID从int更改为string非常简单

 public static class GroupEnumerable { public static IList BuildTree(this IEnumerable source) { var groups = source.GroupBy(i => i.parentKey); var roots = groups.FirstOrDefault(g => g.Key==null).ToList(); if (roots.Count > 0) { var dict = groups.Where(g => g.Key!=null).ToDictionary(g => g.Key, g => g.ToList()); for (int i = 0; i < roots.Count; i++) AddChildren(roots[i], dict); } return roots; } private static void AddChildren(node node, IDictionary> source) { if (source.ContainsKey(node.key)) { node.Children = source[node.key]; for (int i = 0; i < node.Children.Count; i++) AddChildren(node.Children[i], source); } else { node.Children = new List(); } } }