遍历对象的所有后代 [英] Traversing all descendants of an object
问题描述
遍历对象的所有后代时遇到问题。
I'm having problems with traversing all descendants of an object.
以下代码中的'unit'
类型为 Unit
在我的程序中。它具有属性 ChildUnits
,该属性返回该单元子代的 List< Unit>
。
The 'unit'
in the code below is of type Unit
in my program. It has a property ChildUnits
which returns a List<Unit>
of the children of the unit.
我可以成功地对孩子进行操作。然后我检查那些孩子是否有孩子,如果他们也可以,我也可以对他们进行手术。
I can successfully perform operations on the children. Then I check if those children have children, and if they do I can perform operations on them as well.
但是,我需要检查所有后代如果有更多的深度,则不仅仅是孙子孙辈。除了下面的代码,我还使用了while循环,但是它确实很乱,所以我省略了。
However, I need to check all descendants in case there is more depth than just grandchildren. I had a go with while loops in addition to the code below but it got really messy so I left it out.
这是我恢复为的代码:
foreach (var child in unit.ChildUnits)
{
//do something here with the child (I know it sounds dodgy).
bool hasMoreChildren = child.ChildUnits.Count != 0;
if(hasMoreChildren)
{
foreach (var descendant in child.ChildUnits)
{
//do something here with the descendant.
}
}
}
我可以再上一层较深,因为一个单位比该单位更深。但这不是一个干净的解决方案。
I could just go another level deep as it's relatively rare for a unit to have more depth than that. But that's not a clean solution.
我想我可能需要使用图遍历算法和/或递归,但是我想就如何最有效地解决此问题提供一些建议。
I think I might need to use a graph traversal algorithm and/or recursion perhaps, but I would like some advice on how to solve this problem most efficiently.
编辑:是否可以在不定义新函数/方法的情况下执行此操作?
推荐答案
编辑:是否可以在不定义新函数/方法的情况下执行此操作?
Is it possible to do this without defining a new function/method?
您可以使用匿名方法...这不完全是未定义新方法,我知道:)
You could use an anonymous method...which is not exactly "not defining a new method", I know :)
但是,还有另一种方法您应该注意的问题:循环引用... 即使您认为不会有任何问题
However, there's another issue you should take care of: Circular references... even if you dont think there will be any
这是一个实现,没有定义任何新方法
Here's an implementation, without defining any new method
Action<IEnumerable<Unit>> process = null;
var processed = new HashSet<Unit>();
process = list => {
foreach(var u in list.Where (processed.Add))
{
// do something here with u
//... and then process children
process(u.ChildUnits);
}
};
process(myList); // do the actual processing
这篇关于遍历对象的所有后代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!