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.
Jon skeet
source share