Nathan
Nathan

Reputation: 979

Help with recursion and returning value

This is an extension of a previously posted question. I'm trying to recursively build a string. I need to change the function below to do this - each recursion of the function generates the desired string, but I need to concat these together and return the whole string. 'related' is passed into the function as an empty string and I thought the way I was using string.Format would append each recursion to the 'related' string? Apparently not.

Not sure how...

private string getRelatedNews(Taxonomy taxData, string related, string contentTitle)
{
    foreach (TaxonomyItemData item in taxData.TaxonomyItems)
        {
            if (taxData.TaxonomyName.Equals(contentTitle) && taxData.TaxonomyItemCount != 0)
            {
                related = string.Format("{0}<li><a href='{1}'\">{2}</a></li>", related, item.Link, item.Name);
            }                   
        }
    // Show all its sub categories
    foreach (TaxonomyData cat in taxData.Taxonomy)
        {   
            getRelatedNews(cat, related, contentTitle);
        }

    return(related);

}

Upvotes: 0

Views: 3348

Answers (2)

Bhavik Goyal
Bhavik Goyal

Reputation: 2796

Well try this...

related = getRelatedNews(cat, related, contentTitle);

I am not sure about your logic and flow of the program... then also I think recursive function must be called like this....

private string getRelatedNews(Taxonomy taxData, string related, string contentTitle)
{
    foreach (TaxonomyItemData item in taxData.TaxonomyItems)
        {
            if (taxData.TaxonomyName.Equals(contentTitle) && taxData.TaxonomyItemCount != 0)
            {
                related = string.Format("{0}<li><a href='{1}'\">{2}</a></li>", related, item.Link, item.Name);
            }                   
        }
    // Show all its sub categories
    foreach (TaxonomyData cat in taxData.Taxonomy)
        {   
            related = getRelatedNews(cat, related, contentTitle);
        }

    return(related);

}

Upvotes: 0

JoDG
JoDG

Reputation: 1356

foreach (TaxonomyData cat in taxData.Taxonomy)
    {   
        getRelatedNews(cat, related, contentTitle);
    }

should be

foreach (TaxonomyData cat in taxData.Taxonomy)
    {   
        related = getRelatedNews(cat, related, contentTitle);
    }

because strings are immutable.

Upvotes: 5

Related Questions