多层次父子排序 [英] multi level parent child sorting

查看:155
本文介绍了多层次父子排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目列表


  • ID名称PARENTID

  • 1 ABC 0(1级)

  • 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,

abc, aaa, def, mno, g jkl, vwx,

这是我想要的父(升序名称的顺序),其子女(在名称升序排列),儿童subchildren(升序孩子的顺序)等,直至最后一级,然后再父。
我有

that is i want parent (ascending order of name), its children (in ascending order of name), subchildren of children (ascending order of child) and so on till the last level and then again parent. I have

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

But sorts the list as abc, jkl, vwx, aaa, def, g mno, pqr

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

Can anybody let me know where am i going wrong.

推荐答案

下面是一个使用堆栈完整的解决方案。这可能确实有所改进,但它的一般算法。

Here is a full solution using a stack. This could definitely be improved on but it's the general algorithm.

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

这篇关于多层次父子排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆