4

我有一个物品清单

  • ID 名称 ParentID
  • 1 abc 0 (level1)
  • 2 定义 1
  • 3吉1
  • 4 jkl 0
  • 5 个月 2
  • 6 pqr 5
  • 7 一个 1
  • 8 大众 0

我希望列表排序为

abc, aaa, def, 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

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

4

2 回答 2

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;
    }
于 2012-09-17T22:20:21.813 回答
0

首先按子名称排序,然后按父 ID 排序组,否则,您现在得到的输出是绝对正确的,因为一旦记录被分组,它们仅在分组内排序。

于 2012-09-17T22:21:25.730 回答