所以我有一个已定义的特定类的列表,假设IList<Element> A;
Element类具有IList<Children> b;
B列表从文件获取数据。B可以具有包含包含列表等的列表的列表。“递归”或B可以只有一个列表,即B嵌套列表可以不同
我想遍历所有清单。有没有办法做到这一点?
该幼稚的做法是简单地堆递归-这是许多常见方案罚款:
class A {
List<B> _theList;
void DoTheThing() {
foreach(var b in _theList) b.DoTheThing();
}
}
class B {
List<B> _innerItems;
void DoTheThing() {
DoTheThingAtThisLevel();
// and now recurse
foreach(var inner in _innerItems) inner.DoTheThing();
}
}
对于非常深的列表,这可能是一个问题-由于堆栈可能变得太大;在这种情况下,使用本地队列或堆栈并将其用于逻辑状态可以避免以下情况:
class A {
List<B> _theList;
void DoTheThing() {
var queue = new Queue<B>();
foreach (var b in _theList)
queue.Enqueue(b);
while (queue.Count != 0)
{
var b = queue.Dequeue();
b.ProcessThisLevelOnly();
// now we do the logical recursion here
foreach (var inner in b.Items)
queue.Enqueue(inner);
}
}
}
您可以根据深度优先或宽度优先使用堆栈与队列。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句