您的位置:首页 > 游戏 > 手游 > C# 将字符串数组以树型结构化

C# 将字符串数组以树型结构化

2024/10/6 6:02:31 来源:https://blog.csdn.net/ftfmatlab/article/details/140688194  浏览:    关键词:C# 将字符串数组以树型结构化

例如字符串数组:

string[] arr = { "1","3-4-5-6-7", "2","3-4","3-4-5","3-4-5-6", "3", "6", "4", "6-1", "6-2", "5", "6-1-1","1-1","2-1", "1-2-2", "1-1-2", "2-2","1-1-1" };

目的想要树型结构化:

下面开始实现:

先定义一个TreeNode类

 public class TreeNode{public string Value { get; set; }public List<TreeNode> Children { get; set; }public TreeNode(string value){Value = value;Children = new List<TreeNode>();}}

具体实现

TreeNode root = new TreeNode("root");
Dictionary<string, TreeNode> nodesMap = new Dictionary<string, TreeNode>();
foreach (var item in arr)
{if (item.Contains("-")){// 如果元素包含"-",则拆分并构建层级关系string[] parts = item.Split('-');TreeNode currentNode = root;string parentPath = "";for (int i = 0; i < parts.Length; i++){string part = parts[i];string fullPath = parentPath + (string.IsNullOrEmpty(parentPath) ? "" : "-") + part;if (!nodesMap.TryGetValue(fullPath, out TreeNode childNode)){childNode = new TreeNode(part);if (currentNode.Children == null)currentNode.Children = new List<TreeNode>();currentNode.Children.Add(childNode);nodesMap[fullPath] = childNode;}currentNode = childNode;parentPath = fullPath;}}else{// 如果元素不包含"-",则添加为根节点的子节点if (!nodesMap.ContainsKey(item)){TreeNode node = new TreeNode(item);root.Children.Add(node);nodesMap[item] = node;}}
}

打印:

public static void PrintTree(TreeNode node, int level){Console.WriteLine(new string(' ', level * 2) + node.Value);foreach (var child in node.Children){PrintTree(child, level + 1);}}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com