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);
            }
        }
相关推荐
数据的世界017 小时前
使用Avalonia UI实现DataGrid
c#
hihaojie9 小时前
异常的使用
c#·总结
powershell 与 api10 小时前
C#,shell32 + 调用控制面板项(.Cpl)实现“新建快捷方式对话框”(全网首发)
开发语言·windows·c#·.net
Kelvin_Ngan13 小时前
C#从XmlDocument提取完整字符串
c#
iqay15 小时前
【C语言】填空题/程序填空题1
c语言·开发语言·数据结构·c++·算法·c#
中游鱼1 天前
C# 数组和列表的基本知识及 LINQ 查询
c#·linq·数组·数据处理·list数列
32码奴1 天前
C#基础知识
开发语言·c#
来恩10031 天前
C# 类与对象详解
开发语言·c#
Dr.勿忘1 天前
C#面试常考随笔8:using关键字有哪些用法?
开发语言·unity·面试·c#·游戏引擎
xcLeigh1 天前
WPF进阶 | WPF 数据绑定进阶:绑定模式、转换器与验证
c#·wpf