简体   繁体   English

我可以使用什么算法在C#中对此分支列表进行排序?

[英]What algorithm can I use for sorting this branching List in C#?

I'm trying to create an ordered branching list of categories, so I can find any subcategories and add "-" at the start; 我正在尝试创建一个有序的分类分类列表,所以我可以找到任何子类别并在开头添加"-" ; and also any subcategories that category might have and add "--" etc. 以及该类别可能具有的任何子类别并添加"--"等。

My test class properties looks like this: 我的测试类属性如下所示:

    public int Id { get; set; }
    public int OrderInList { get; set; }
    public int ParentId { get; set; }
    public IList<TestCategories> Subcategories { get; set; }

Example: 例:

Books
-Special Offers
--Fiction
-eBooks 
--Pdf
--Mobi
Maps
-United Kingdom
--Cumbria
--West Yorkshire

I have a default root level category with Id: 1 , ParentId: 1 and OrderInList: 1 . 我有一个默认的根级别类别, Id: 1ParentId: 1OrderInList: 1
So the order of the above would look something like: 所以上面的顺序看起来像:

Id   | ParentId  |  OrderInList   
 2         1             1      //Books
 3         2             1      //-Special Offers
 4         3             1      //--Fiction
 5         2             2      //-eBooks
 6         5             1      //--Pdf
 7         5             2      //--Mobi
 8         1             2      //Maps
 9         8             1      //-United Kingdom
 10        9             1      //--Cumbria
 11        9             2      //--West Yorkshire

How can I sort a completely unordered list to look something like the above? 如何对完全无序的列表进行排序以查看类似于上面的内容?

This kind of sorting is called Topological Sorting . 这种排序称为拓扑排序 The easiest way to sort a list topologically is using a depth-first recursive search: the order in which you leave the nodes is reverse topological. 在拓扑上对列表进行排序的最简单方法是使用深度优先递归搜索:离开节点的顺序是反向拓扑。 If you need to know the depth of a node in a tree so that you know how many dashes to place in front of a name, you can add an int level variable to your depth-first recursive method. 如果您需要知道树中节点的深度,以便知道要在名称前放置多少个破折号,则可以在深度优先递归方法中添加一个int level变量。

You can borrow an implementation from Rosetta Code - it does not have one in C#, but the one in Java should be easy enough to translate. 您可以从Rosetta Code借用一个实现 - 它在C#中没有一个实现,但Java中的实现应该很容易翻译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM