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);
            }
        }
相关推荐
Polevne4 小时前
C# SFTP客户端实现文件传输
c#·ssh
samble5 小时前
从零搭建灌装监控系统(四):深色主题与样式系统,ResourceDictionary 统一管理
c#·wpf·mvvm·样式·工业控制
cjp5605 小时前
024 . WPF MVVM类封装优化
c#
淡海水16 小时前
13-04-面试-源码级深度追问链
数据结构·unity·面试·c#·游戏引擎·源码·il2cpp
asdzx6717 小时前
如何使用 C# 提取 PPT 文本与图片
c#·ppt·提取文本
2501_930707781 天前
使用C#代码使用条件格式为 Excel 隔行设置颜色
c#·excel
何以解忧唯有撸码1 天前
【开源】c#造个轮子-日程安排工具
c#·自定义控件
周杰伦fans1 天前
CAD菜单栏和工具栏都不见了,怎么显示?
其他·c#
曹牧1 天前
C#:HashSet<T> 去重
c#
czhc11400756631 天前
起点、口径与因果:今天用错的七把尺子
c#