0

Sorry, this is pretty basic but for the life of me I have not been able to solve it:

I have this:

public static IHtmlString HrefLangLinks(this PageData currentPage)
{
    var availablePageLanguages = currentPage.ExistingLanguages.Select(culture => culture.Name).ToArray();

    foreach (string listitem in availablePageLanguages)
    {
        var Output = string.Join(",", listitem);
    } 

    // Dictionary<String, String>
    return new HtmlString(Output.ToString());
}

I would like to get the results of the foreach loop outputted in the return value. But Visual Studio informs me that "Output" (the instance in my return value) does not exist in the current context.

I thought I could solve this by adding var Output =""; outside of my foreach loop but that did not work.

2
  • 1
    Define "That didn't work" Commented Apr 7, 2019 at 19:42
  • 1
    Try return new HtmlString(string.Join(",", availablePageLanguages)). Commented Apr 7, 2019 at 19:45

1 Answer 1

2

Define Output before going into the foreach loop and then assign it a value:

var Output = "";

foreach (string listitem in availablePageLanguages)
{
    Output = string.Join(",", listitem);
} 

Apart from that I wonder if you really need a for loop in this case as you should also be able to this at once if availablePageLanguages is an array of string (string[]):

var Output = String.Join(" ", availablePageLanguages));
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for that. I was not paying attention to the "var" in my foreach loop which was creating a new instance of the variable, correct?
If I am not mistaken, this solution will only include the last listitem from availablePageLanguages (since Output is overwritten for each listitem). I believe that is what OP meant by "did not work). As it turns out, we both had the same idea. I think your edit is the correct solution.

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.