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

C#新手:从对象列表构建简易对象列表——列表间转换实现

处理扁平分类列表转树形结构的解决方案

嘿,我猜你是想把从API拿到的扁平分类列表转换成层级清晰的树形结构吧?这种需求太常见了,我来给你捋捋可行的解决思路和代码示例:

核心逻辑拆解

这类数据的核心关联是ParentID和CategoryID,我们可以分两步走:

  • 先把所有分类节点用CategoryID做键,存到一个映射表里,方便快速查找父节点
  • 遍历每个节点,把它挂载到对应父节点的子节点列表中,最后收集所有没有父节点的顶级节点,就是最终的树形结构

补全后的示例数据

先把你给出的示例补全成更完整的结构,方便演示:

CategoryID      Name            ParentID
1               Tools           null
2               Hand Tools      1
3               Power Tools     1
4               Hammer          2
5               Drill           3

JavaScript实现示例

// 假设从API拿到的原始数据
const rawCategories = [
  { CategoryID: 1, Name: "Tools", ParentID: null },
  { CategoryID: 2, Name: "Hand Tools", ParentID: 1 },
  { CategoryID: 3, Name: "Power Tools", ParentID: 1 },
  { CategoryID: 4, Name: "Hammer", ParentID: 2 },
  { CategoryID: 5, Name: "Drill", ParentID: 3 }
];

function buildTree(categories) {
  const nodeMap = {};
  const treeRoots = [];

  // 第一步:构建节点映射表,同时给每个节点初始化children数组
  categories.forEach(cat => {
    nodeMap[cat.CategoryID] = { ...cat, children: [] };
  });

  // 第二步:挂载子节点到对应的父节点
  categories.forEach(cat => {
    const currentNode = nodeMap[cat.CategoryID];
    if (cat.ParentID && nodeMap[cat.ParentID]) {
      // 如果有有效父ID,就挂到父节点的children里
      nodeMap[cat.ParentID].children.push(currentNode);
    } else {
      // 没有父ID的就是根节点,直接加入根列表
      treeRoots.push(currentNode);
    }
  });

  return treeRoots;
}

// 生成树形结构
const categoryTree = buildTree(rawCategories);
console.log(categoryTree);

C#实现示例

如果是用C#开发,逻辑完全一致,只是语法不同:

public class Category
{
    public int CategoryID { get; set; }
    public string Name { get; set; }
    public int? ParentID { get; set; }
    public List<Category> Children { get; set; } = new List<Category>();
}

public List<Category> BuildCategoryTree(List<Category> categories)
{
    var categoryDict = categories.ToDictionary(c => c.CategoryID);
    var treeRoots = new List<Category>();

    foreach (var category in categories)
    {
        if (category.ParentID.HasValue && categoryDict.ContainsKey(category.ParentID.Value))
        {
            categoryDict[category.ParentID.Value].Children.Add(category);
        }
        else
        {
            treeRoots.Add(category);
        }
    }

    return treeRoots;
}

避坑提示

  • 一定要处理ParentID为null、0或者无效值的情况,这些都要当作根节点处理
  • 如果API返回的数据里有无效的ParentID(比如指向一个不存在的CategoryID),记得加判断避免抛出异常
  • 如果需要遍历树形结构展示,可以用递归或者迭代的方式(深度优先/广度优先)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:26:05