condition in recursion - best practise

Posted by mo on Stack Overflow See other posts from Stack Overflow or by mo
Published on 2010-04-29T17:12:12Z Indexed on 2010/04/29 17:17 UTC
Read the original article Hit count: 425

Filed under:
|
|
|

hi there!

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;
            break;
        }
        else
        {
            child = Find(wannabe, criteria);
        }
    }

    return child;
}

or

Child Find(Parent parent, object criteria)
{
    Child child = null;
    var conditionator = from c 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 u think, any better ideas? i'm looking for the niciest solution :D

mo

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET