0

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);

}
1
  • 2
    One issue with this is that you will be creating numerous strings that are thrown away (increasing pressure on the GC). Look into using StringBuilder to build a string only once. Commented Apr 8, 2011 at 4:19

2 Answers 2

5
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.

Sign up to request clarification or add additional context in comments.

1 Comment

Bingo. Gives exactly the result I expected. Thank you.
0

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);

}

1 Comment

he is alreadt concatenating using string.Format, you should not be doing related = related + string.Format....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.