Conditional in recursion is best practice
what's the best practice for breaking 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 = Find(wannabe, criteria);
}
}
return child;
}
what do you think any better ideas? I am looking for the nicest solution: D
mo
+2
a source to share
2 answers
Linq can be more concise, but it can be harder 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 children
).FirstOrDefault(); // We're only interested in the first child that matches the criteria or null if none found
}
+8
a source to share
You don't have to deal with it IEnumerator
yourself, which is why option 3 is missing.
Option 2 doesn't work. It continues regardless of the search for a match, and if the last child does not match and its children do not contain a match, then the result will be null
even if there was a previous match.
Option 1 seems to be the cleanest if you mind multiple operators return
.
+1
a source to share