简体   繁体   English

返回时,完全停止递归

[英]Stop the recursion completely when returning something

I do recursion to find a long value within a List with multiple children that also can have children. 我做递归以在List中找到一个具有多个子节点的长值,这些子节点也可以有子节点。

following method: 以下方法:

public TaxonomyData getTaxonomyData(long taxId, List<TaxonomyData> TaxonomyTree, TaxonomyData output)
{
    //find taxid in the taxonomy tree list and return the taxonomydata

    foreach (TaxonomyData td in TaxonomyTree)
    {
        if (td.TaxonomyId == taxId)
        {
                output = td;
                //return td; => when doing a return here means I already found a match so it is not necessary to do all the recursion.
        }
        else if (td.Taxonomy.Length > 0)
        {
            getTaxonomyData(taxId, td.Taxonomy.ToList(), output);
        }
    }

    return output;
}

Is it possible when I do return td; 当我return td;时有可能return td; (see commented row) that my whole recursion stops? (见注释行)我的整个递归停止了?

Thanks 谢谢

I suspect you want something like: 我怀疑你想要的东西:

public TaxonomyData GetTaxonomyData(long taxId, IEnumerable<TaxonomyData> tree)
{
    foreach (TaxonomyData td in tree)
    {
        if (td.TaxonomyId == taxId)
        {
            return td;
        }
        else
        {
            // See if it's in the subtree of td
            TaxonomyData data = GetTaxonomyData(taxId, td.Taxonomy);
            if (data != null)
            {
                return data;
            }
        }
    }
    // Haven't found it anywhere in this tree
    return null;
}

Each return only returns one level, but by checking the return value in the else clause, we can return all the way up the stack when we find the right value. 每个return只返回一个级别,但是通过检查else子句中的返回值,当我们找到正确的值时,我们可以一直返回堆栈。

The final result returned to the caller will be a null reference if it hasn't been found. 如果尚未找到,则返回给调用者的最终结果将是空引用。

Note that I've removed the "output" parameter, which wouldn't have been effective anyway as it wasn't a ref parameter, and isn't as clear as just using the return value. 请注意,我已经删除了“输出”参数,因为它是不是这不会是有效的反正ref参数,是不是使用返回值一样清晰。

A linq extension solution i came up with, probably slower but there you go.. 我提出了一个linq扩展解决方案,可能比较慢,但你去了..

public static class Ext
{
    public static T SingleOrDefault<T>(this IEnumerable<T> enumerable,Func<T,bool> predicate, Func<T,T> defaultSelector)
        where T : class
    {   
        return enumerable.SingleOrDefault(predicate) ?? enumerable.SkipWhile<T>(t=>defaultSelector(t) == null).Select(defaultSelector).SingleOrDefault();
    } 

    public static TaxonomyData Get(this IEnumerable<TaxonomyData> tree, int taxId)
    {
        return tree.SingleOrDefault(t=> t.TaxonomyId == taxId,t=>t.Taxonomy.Get(taxId));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM