递归条件 - 最佳实践

时间:2010-04-29 17:12:13

标签: c# .net recursion conditional

打破循环的最佳做法是什么? 我的想法是:

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;
}

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;
}

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;
}

您认为什么,更好的想法? 我正在寻找最有效的解决方案:D

2 个答案:

答案 0 :(得分:8)

Linq可能更简洁,但可能更难理解!

    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
    }

答案 1 :(得分:1)

您无需自己处理IEnumerator,因此选项3已经用完。

选项2不起作用。无论找到匹配项,它都会继续,如果最后一个孩子不匹配且其子项不包含匹配项,那么即使之前有匹配项,结果也会为null

选项1似乎是最干净的,假设您反对多个return语句。