一千萬個為什麽

搜索

如何使用集合實現類別層次結構

我有大約200個嵌套的類別。我目前正在閱讀有關C5泛型庫的文檔。我不確定C5庫是否過度殺傷。我正在考慮將所有自定義算法轉換為C5實現。

這就是我需要的。如果選擇某一類別,我需要找到其父母,兄弟姐妹,直接子女和所有孩子。

這就是我設置它的方式。找到:

Parents: I start from the current location then loop through the list and find the current parent. When I find the parent I loop through the whole list again to find the next parent and so on.

Siblings: I loop through the whole list and find all the nodes that have the same parent as the choosen node.

direct children: I loop through the whole list and find all nodes that is a parent of the choosen node.

All Children: This one took me a while to figure out. But I used recursion to find all children of the choosen node.

有沒有更好的方法來實現這樣的事情?

最佳答案

Why does it have to be collection-based? I would just create class Category with properties Category Parent and IList Children. That way, finding parent or predecessors is really easy (and fast!), finding children too, siblings are children of parent except the current category, so they are easy too. And finding descendants is trivial recursion.

轉載註明原文: 如何使用集合實現類別層次結構