condition in recursion - best practise
what's the best practise to break a loop? my ideas were:
Child Find(Parent parent, object criteria)
{
Child child = null;
foreach(Child wannabe in parent.Childs)
{
if (wannabe.Match(criteria))
{
child = wannabe;
}
else
{
child = Find(wannabe, criteria);
}
if (child != null) break;
}
return child;
}
or
Child Find(Parent parent, object criteria)
{
Child child = null;
var conditionator = from c in parent.Childs where child != null select c;
foreach(Child wannabe in conditionator)
{
if (wannabe.Match(criteria))
{
child = wannabe;
}
else
{
child = Find(wannabe, criteria);
}
}
return child;
}
or
Child Find(Parent parent, object criteria)
{
Child child = null;
var enumerator = parent.Childs.GetEnumerator();
while(child != null && enumerator.MoveNext())
{
if (enumerator.Current.Match(criteria))
{
child = wannabe;
}
else
{
child = Fin开发者_StackOverflow中文版d(wannabe, criteria);
}
}
return child;
}
what do u think, any better ideas? i'm looking for the niciest solution :D
mo
Linq may be more terse, but can be more difficult to understand!
Child Find(Parent parent, object criteria)
{
return parent.Childs.Select( // Loop through the children looking for those that match the following criteria
c => c.Match(criteria) // Does this child match the criteria?
? c // If so, just return this child
: this.Find(c, criteria) // If not, try to find it in this child's children
).FirstOrDefault(); // We're only interested in the first child that matches the criteria or null if none found
}
There's no need for you to deal with the IEnumerator
yourself, so option 3 is out.
Option 2 does not function. It continues regardless of finding a match, and if the last child is not a match and its children do not contain a match, then the result will be null
even if there was a prior match.
Option 1 seems the cleanest, assuming you object to multiple return
statements.
精彩评论