I've got a tree-like structure. Each element in this structure should be able to return a Enumerable of all elements it is root to. Let's call this method IEnumerable<Foo> GetAll()
. So if we have
A <-- topmost root
/
/
B C
/ /
D E F G
a call to GetAll
on element C
returns {C, F, G}
(fixed order of elements would be nice, but is not needed). I guess everybody knew that already.
The current implementation of GetAll
looks like this:
public IEnumerable<Foo> GetAll ()
{
yield return this;
foreach (Foo foo in MyChildren) {
foreach (Foo f in foo.GetAll ()) {
yield return f;
}
}
}
In an earlier implementation, I returned a List and added the child-foos using List.AddRange()
.
My question is if the version using yield is correcly implemented or if it should be improved (esp. in terms of performance). Or is this just bad and I should stick to List
s (or ReadOnlyCollections
) instead?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…