You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中合并嵌套List<Path>的重复路径节点

合并重复嵌套Path节点的实现方案

核心思路

要实现重复路径节点的合并,关键是先将所有嵌套的Path结构扁平化为根到叶子的路径序列,再通过逐层匹配的方式重新构建唯一的嵌套结构——每一层优先查找已存在同名节点,存在则复用,不存在则创建新节点。

步骤1:将嵌套Path转换为扁平化路径列表

实现递归方法,把单个Path对象拆解成从根到叶子的名称数组:

public static IEnumerable<List<string>> FlattenPaths(Path path)
{
    if (path?.Items == null || !path.Items.Any())
    {
        return new List<List<string>> { new List<string> { path.Name } };
    }

    var result = new List<List<string>>();
    foreach (var item in path.Items)
    {
        foreach (var subPath in FlattenPaths(item))
        {
            subPath.Insert(0, path.Name);
            result.Add(subPath);
        }
    }
    return result;
}

步骤2:从扁平化路径构建合并后的嵌套结构

用字典高效查找同层级已存在节点,避免重复创建:

public static List<Path> MergePaths(List<Path> originalPaths)
{
    var allFlatPaths = originalPaths.SelectMany(p => FlattenPaths(p)).ToList();
    var rootNodes = new List<Path>();
    var rootDict = new Dictionary<string, Path>();

    foreach (var flatPath in allFlatPaths)
    {
        Path currentParent = null;
        Dictionary<string, Path> currentLevelDict = rootDict;
        List<Path> currentLevelList = rootNodes;

        foreach (var name in flatPath)
        {
            if (!currentLevelDict.TryGetValue(name, out var existingNode))
            {
                existingNode = new Path { Name = name, Items = new List<Path>() };
                currentLevelList.Add(existingNode);
                currentLevelDict[name] = existingNode;
            }

            currentParent = existingNode;
            currentLevelDict = currentParent.Items.ToDictionary(n => n.Name);
            currentLevelList = currentParent.Items.ToList();
        }

        if (currentParent != null)
        {
            currentParent.Items = null;
        }
    }

    return rootNodes;
}

步骤3:使用示例

将原始重复路径列表传入方法,即可得到合并后的结构:

// 原始重复路径集合
var originalList = new List<Path>
{
    new Path { Name = "FirstRoot", Items = new List<Path> { /* 嵌套节点 */ } },
    new Path { Name = "FirstRoot", Items = new List<Path> { /* 嵌套节点 */ } },
    // 其他重复路径...
};

// 获取合并后的唯一嵌套结构
var mergedList = MergePaths(originalList);

补充说明

  • 扁平化步骤简化了嵌套结构的遍历逻辑,能清晰获取每条完整路径
  • 字典查找保证了同层级节点的唯一性,提升了合并效率
  • 自动将叶子节点的Items设为null,与目标结构完全匹配

内容的提问来源于stack exchange,提问作者prvn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 15:17:52