多级父子排序

时间:2012-09-17 22:13:49

标签: c# asp.net linq hierarchical-data

我有一个项目列表

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

我想将列表排序为

ABC, AAA, 闪避, MNO, GHI, JKL, VWX,

即我想要父(名字的升序),它的子(按姓名的升序排列),子女的子女(孩子的升序)等等到最后一级然后再是父母。 我有

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

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

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

3 个答案:

答案 0 :(得分: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;
    }

答案 1 :(得分:0)

首先按子名称排序,然后按父母ID排序,因为否则你现在拥有的输出是绝对正确的,因为一旦记录被分组,它们只在分组内排序

答案 2 :(得分:0)

这是一个递归问题,前几天有一个类似的问题被问到,一个有趣的答案是this one