Stop recursion completely by returning something

I am doing a recursion to find a long value in a list with several children that can also have children.

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; (see numbered line) that all my recursion stops?

thanks

+8
c # recursion
source share
2 answers

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 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 returns only one level, but by checking the return value in the else clause, we can return the entire path to the stack when we find the desired value.

The final result returned to the caller will be an empty link if it is not found.

Note that I removed the "output" parameter, which would not be effective in any case, since it was not a ref parameter and is not as clear as just using the return value.

+14
source share

The linq extension solution I came up with is probably slower, but there you go.

 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)); } } 
+1
source share

All Articles