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

按父ID分组Schedule列表元素 并按Prompt字段排序构建树形结构

树形结构分组+按Prompt排序的实现方案

针对你提出的需求——把Schedule列表按ParentId分组构建树形结构,同时全层级按Prompt字段递增排序,我整理了一套清晰的实现步骤和C#代码示例:

核心思路

  1. 快速映射节点:先把所有Schedule对象按Id存入字典,这样能以O(1)时间找到任意父节点,避免频繁遍历查找。
  2. 挂载子节点到父节点:遍历所有节点,将非根节点(ParentId非空)添加到对应父节点的Children集合中。
  3. 全层级排序:对每个节点的Children集合按Prompt升序排序,同时顶层根节点也按Prompt排序。

完整代码实现

public class Schedule 
{ 
    public string Id { get; set; }
    public int Prompt { get; set; }
    public int Hierarchy { get; set; }
    public string? ParentId { get; set; }
    public virtual ICollection<Schedule> Children { get; set; } = new List<Schedule>(); // 提前初始化避免空引用
}

public static class ScheduleTreeBuilder
{
    public static List<Schedule> BuildSortedHierarchicalTree(List<Schedule> schedules)
    {
        // 1. 构建Id到Schedule的映射字典,快速定位父节点
        var scheduleLookup = schedules.ToDictionary(s => s.Id);

        // 2. 遍历所有节点,将子节点挂载到对应父节点下
        foreach (var schedule in schedules)
        {
            if (!string.IsNullOrEmpty(schedule.ParentId) && scheduleLookup.TryGetValue(schedule.ParentId, out var parentSchedule))
            {
                parentSchedule.Children.Add(schedule);
            }
        }

        // 3. 对每个节点的子节点按Prompt升序排序(包括所有层级)
        foreach (var schedule in schedules)
        {
            schedule.Children = schedule.Children.OrderBy(child => child.Prompt).ToList();
        }

        // 4. 返回排序后的顶层根节点列表
        return schedules
            .Where(s => string.IsNullOrEmpty(s.ParentId))
            .OrderBy(root => root.Prompt)
            .ToList();
    }
}

代码说明

  • 空引用防护:在Schedule类里给Children默认初始化List<Schedule>,避免添加子节点时出现NullReferenceException。
  • 无效ParentId处理:通过scheduleLookup.TryGetValue判断父节点是否存在,忽略无效的父节点引用(你也可以根据需求改成抛出异常)。
  • 全层级排序:不管树的层级有多深,所有节点的子节点都会按Prompt递增排列,顶层根节点同样遵循这个规则。

使用示例

假设你有如下测试数据:

var testSchedules = new List<Schedule>
{
    new Schedule { Id = "root2", Prompt = 2, Hierarchy = 1, ParentId = null },
    new Schedule { Id = "root1", Prompt = 1, Hierarchy = 1, ParentId = null },
    new Schedule { Id = "child1-1", Prompt = 1, Hierarchy = 2, ParentId = "root1" },
    new Schedule { Id = "child1-2", Prompt = 2, Hierarchy = 2, ParentId = "root1" },
    new Schedule { Id = "grandchild1-1-1", Prompt = 1, Hierarchy = 3, ParentId = "child1-1" }
};

var sortedTree = ScheduleTreeBuilder.BuildSortedHierarchicalTree(testSchedules);

最终得到的树形结构会是:

  • root1(Prompt=1)
    • child1-1(Prompt=1)
      • grandchild1-1-1(Prompt=1)
    • child1-2(Prompt=2)
  • root2(Prompt=2)

完全符合按Prompt递增排序的树形展示需求。

内容的提问来源于stack exchange,提问作者Rene M.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:24:20