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

如何在C#中获取自引用嵌套模型的最底层子项ID

解决自引用模型获取最底层子项modelId的问题

你的问题出在只筛选了顶层的无子女节点,没有遍历嵌套的子层级结构。要获取所有层级的最底层(叶子)节点,需要递归或迭代遍历整个树形结构:

方法一:递归遍历(简洁直观)

先写一个递归方法遍历所有节点,收集叶子节点的modelId:

private static IEnumerable<string> GetLeafModelIds(IEnumerable<Model> models)
{
    foreach (var model in models)
    {
        // 当前节点无子女,属于最底层,返回其modelId
        if (!model.HasChild)
        {
            yield return model.modelId;
        }
        else
        {
            // 有子女则递归遍历子节点集合
            if (model.Child != null)
            {
                foreach (var childId in GetLeafModelIds(model.Child))
                {
                    yield return childId;
                }
            }
        }
    }
}

调用方式:

var modelIds = GetLeafModelIds(Models).ToList();

方法二:迭代遍历(避免栈溢出)

如果你的模型嵌套层级极深,递归可能引发栈溢出,这时用迭代方式更安全:

private static IEnumerable<string> GetLeafModelIdsIterative(IEnumerable<Model> models)
{
    var stack = new Stack<Model>(models);
    while (stack.Count > 0)
    {
        var model = stack.Pop();
        if (!model.HasChild)
        {
            yield return model.modelId;
        }
        else
        {
            if (model.Child != null)
            {
                // 将子节点压入栈,继续遍历
                foreach (var child in model.Child)
                {
                    stack.Push(child);
                }
            }
        }
    }
}

调用方式和递归版一致:

var modelIds = GetLeafModelIdsIterative(Models).ToList();

注意事项

  • 要判断Child是否为null,避免空引用异常;
  • HasChild属性需要确保能准确反映节点是否有子项(比如当Child为空集合时,HasChild应该设为false)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 01:37:20