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);
            }
        }
相关推荐
samble1 小时前
从零搭建灌装监控系统(十七):LiveCharts 实时温度曲线
c#·wpf·mvvm·modbus·工业控制
淡海水10 小时前
02-07-原理篇-GC暂停时间的本质
开发语言·unity·c#·gc·暂停时间
小羊没烦恼!11 小时前
OS X 上使用.NET开发应用程序
开发语言·前端·数据库·人工智能·c#·策略模式
Behavior13 小时前
Unity 7.0 Alpha 拆解:编辑器干掉 Mono 换 CoreCLR
c#·unity3d·游戏开发
淡海水13 小时前
02-06-原理篇-增量式GC与并发GC
算法·unity·c#·并发·gc·增量
Vertira14 小时前
C# 函数封装成 DLL,
开发语言·c#
浅尝辄止;15 小时前
设计模式在HIS/LIS医疗系统中的完整实践指南(C#版)
开发语言·设计模式·c#
kimloner1 天前
开源一个 376KB 的 Windows 桌面小工具:便签 + 截图标注 + OCR + 待办提醒(C# / WinForms)
windows·开源·c#·ocr·winforms
阿松爱学习1 天前
【Unity开发】Aspose.PDF的使用
unity·pdf·c#
半亩码田1 天前
C#转Python第4.8篇:正则表达式:Python re 模块 vs C# System.Text.RegularExpressions
python·正则表达式·c#