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

例如字符串数组:

cs 复制代码
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类

cs 复制代码
 public class TreeNode
    {
        public string Value { get; set; }
        public List<TreeNode> Children { get; set; }

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

具体实现

cs 复制代码
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;
        }
    }
}

打印:

cs 复制代码
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);
            }
        }
相关推荐
Panda__Panda3 小时前
docker项目打包演示项目(数字排序服务)
运维·javascript·python·docker·容器·c#
weixin_456904274 小时前
基于.NET Framework 4.0的串口通信
开发语言·c#·.net
Tiger_shl5 小时前
C# 预处理指令 (# 指令) 详解
开发语言·c#
sali-tec6 小时前
C# 基于halcon的视觉工作流-章45-网格面划痕
开发语言·算法·计算机视觉·c#
云草桑10 小时前
C#入坑JAVA 使用XXLJob
java·开发语言·c#
玉夏10 小时前
【每日算法C#】爬楼梯问题 LeetCode
算法·leetcode·c#
云草桑16 小时前
.net AI MCP 入门 适用于模型上下文协议的 C# SDK 简介(MCP)
ai·c#·.net·mcp
工程师00718 小时前
C#中堆和栈的概念
c#·堆和栈
weixin_3077791318 小时前
C#实现MySQL→Clickhouse建表语句转换工具
开发语言·数据库·算法·c#·自动化
CsharpDev-奶豆哥1 天前
ASP.NET中for和foreach使用指南
windows·microsoft·c#·asp.net·.net