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);
            }
        }
相关推荐
ISDF-工软未来3 小时前
C# 泛型简单案例
c#
疯狂的维修5 小时前
C#中一段程序类比博图
c#
时光追逐者7 小时前
C#/.NET/.NET Core技术前沿周刊 | 第 53 期(2025年9.1-9.7)
c#·.net·.netcore
冷冷的菜哥7 小时前
ASP.NET Core使用MailKit发送邮件
后端·c#·asp.net·发送邮件·mailkit
weixin_447103587 小时前
C#之LINQ
c#·linq
ysn111118 小时前
反编译分析C#闭包
c#
one99610 小时前
WPF应用程序中的异常处理
c#·.net·wpf
almighty2711 小时前
C# ObjectListView实现树状文件夹浏览
c#·树状图·objectlistview·c#树状图·文件显示
ccut 第一混17 小时前
c# 调用basler 相机
c#·halcon·basler
TomCode先生17 小时前
c#动态树形表达式详解
开发语言·c#