开发者

Why is this C# loop over a list of strings being weird?

开发者 https://www.devze.com 2023-01-25 20:28 出处:网络
I don\'t consider myself to be the greatest developer in the world, but I thought I could at least loop over a list of strings!

I don't consider myself to be the greatest developer in the world, but I thought I could at least loop over a list of strings!

Here's my function:

    public string liststrings() {

        List<string> strings = new List<string>();
        strings.Add("First");
        strings.Add("Second");
        strings.Add("Third");

        string output = string.Empty;

        for (int i = 0; i < strings.Count(); i++ )
        {
            output += out开发者_如何学JAVAput + strings[i] + "<br />";
        }

        return output;
    }

This function returns the following html:

First<br />
First<br />
Second<br />
First<br />
First<br />
Second<br />
Third<br />

Where are the extra iterations coming from?

FYI: I come from a primarily VB script background and I can do this with an array in VB script without a problem. What different about lists or C# syntax that's fouling this up?

Thanks for any help.


You're adding output twice.

output += output + strings[i] + "<br />";

is equivalent to:

output = output + output + strings[i] + "<br />";

You could use:

output += strings[i] + "<br />";

A better option might be a StringBuilder.


You are adding the whole string back to itself on each iteration, try the following instead:

output += strings[i] + "<br />";


The extra iterations are coming from the fact that you are appending the previous value of output to itself twice.

output += output + strings[i] + "<br />";

I think you want

output = output + strings[i] + "<br />";

or

output += strings[i] + "<br />";

But honestly from what you are doing I would look at the StringBuilder class.


It is recommended to use a StringBuilder object instead of concatenating strings.

...
StringBuilder sb = new StringBuilder();
for( int i = 0; i < strings.Length; i++)
{
    sb.WriteLine("{0}<br />", strings[i]);
}
return sb.ToString();

Note to use the .Length property for pure arrays because it is faster.


You should remove the () after strings.Count. Also, you can use a

foreach(string str in strings)
{
    // etc.
}

Also, as mentioned in other posts, you are adding output twice:

output += output + "something"

is equivalent to

output = output + output + "something"
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号