多级父子排序

Sne*_*thy 4 c# linq asp.net hierarchical-data

我有一个项目清单

  • ID名称ParentID
  • 1 abc 0(level1)
  • 2 def 1
  • 3 ghi 1
  • 4 jkl 0
  • 5分钟2
  • 6 pqr 5
  • 7 aaa 1
  • 8 vwx 0

我希望列表排序为

abc,aaa,def,mno,ghi,jkl,vwx,

这就是我想要的父(升序名称的顺序),其子女(以名称的升序),儿童subchildren(孩子的升序),并以此类推,直到最后一个级别,然后再父.我有

sections = new List<section>( from section in sections
                     group section by section.ParentID into children
                     orderby children.Key
                     from childSection in children.OrderBy(child => child.Name)
                     select childSection);
Run Code Online (Sandbox Code Playgroud)

但将列表排序为abc,jkl,vwx,aaa,def,ghi,mno,pqr

任何人都可以让我知道我哪里出错了.

Joh*_*rer 5

这是使用堆栈的完整解决方案.这肯定可以改进,但它是一般算法.

public class Section
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int ParentID { get; set; }
}
class Program
{
    static void Main(string[] args)
    {
        var sections = new List<Section>
            {
                new Section { ID = 1, Name = "abc", ParentID = 0 },
                new Section { ID = 2, Name = "def", ParentID = 1 },
                new Section { ID = 3, Name = "ghi", ParentID = 1 },
                new Section { ID = 4, Name = "jkl", ParentID = 0 },
                new Section { ID = 5, Name = "mno", ParentID = 2 },
                new Section { ID = 6, Name = "pqr", ParentID = 5 },
                new Section { ID = 7, Name = "aaa", ParentID = 1 },
                new Section { ID = 8, Name = "vwx", ParentID = 0 }
            };

        sections = sections.OrderBy(x => x.ParentID).ThenBy(x => x.Name).ToList();
        var stack = new Stack<Section>();

        // Grab all the items without parents
        foreach (var section in sections.Where(x => x.ParentID == default(int)).Reverse())
        {
            stack.Push(section);
            sections.RemoveAt(0);   
        }

        var output = new List<Section>();
        while (stack.Any())
        {
            var currentSection = stack.Pop();

            var children = sections.Where(x => x.ParentID == currentSection.ID).Reverse();

            foreach (var section in children)
            {
                stack.Push(section);
                sections.Remove(section);
            }
            output.Add(currentSection);
        }
        sections = output;
    }
Run Code Online (Sandbox Code Playgroud)