c# - 递归条件 - 最佳实践

标签 c# .net recursion conditional-statements

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

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

最佳答案

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
    }

关于c# - 递归条件 - 最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2739337/

相关文章:

c# - FileLoadException 未被用户代码处理

C# - 程序员面试挑战 - 接口(interface)和模式编程

c# - 如何在没有 Auth 的情况下连接到 YouTube API?

SQL Server : Recursive Query

Clojure 的递归和 Clojure 的勇敢和真实

c# - WPF DataGrid 页脚行

c# - 关于继承

c# - 如果列在 LINQ 中为空,如何忽略 'where' 和 'order by' 条件

c# - 使用 linq 将多个求和为一种匿名类型?

python 2.7 - 递归斐波那契爆炸