按父ID列出元素列表,然后按另一个字段排序

时间:2018-05-05 01:27:35

标签: c# entity-framework linq

所以我有一个这样的元素列表:

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;}
}

任何元素都可以有n个孩子,他们的孩子有更多的孩子,我试图将数据显示为树,但我也想通过提示字段进行排序;此字段是增量索引,因此所有父项都没有相同的值,但是当您进入其子项时,此索引将返回值= 1,依此类推。

“层次结构”字段用于了解子树在树中的深度

1 个答案:

答案 0 :(得分:0)

一种解决方案是使用遍历树的递归函数并对所有子进行排序。

private IEnumerable<Schedule> Sort(IEnumerable<Schedule> schedules)
{
    var sorted = schedules.OrderBy(s => s.Prompt);

    foreach (var schedule in sorted.Where(s => s.Children != null && s.Children.Any()))
    {
        schedule.Children = Sort(schedule.Children).ToList();
    }

    return sorted;
}

您可以在原始列表中调用:

var schedules = new List<Schedule>(); // get schedules from somewhere
var sorted = Sort(schedules);