Multilevel sorting of parental children

I have a list of items

  • 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

I want the list to sort as

ABC, AAA, Protection, MnO, GHI, JKL, VWX,

that is, I want the parent (ascending order of the name), its children (in ascending order of the name), children of the children (ascending order of the child), etc. to 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); 

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

Someone can tell me where I'm wrong.

+4
source share
3 answers

Here is the complete solution using the stack. This could definitely be improved, but this is a 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; } 
+5
source

First order by the name of the child, and then sort the group by parent identifier, because otherwise, with what you have right now, you get an absolutely accurate result, because as soon as the records have been grouped, they are ordered only within the groups.

0
source

This is a recursion problem, a couple of days ago a similar question was asked, and this was an interesting answer.

0
source

Source: https://habr.com/ru/post/1434720/


All Articles