简体   繁体   English

如何加速foreach结果

[英]how to speed up foreach results

I am making a Windows Forms application, and I want to generate numbers from 0 to 99999. I use the following code to print these numbers:我正在制作一个 Windows 窗体应用程序,我想生成从 0 到 99999 的数字。我使用以下代码打印这些数字:

  private void button1_Click(object sender, EventArgs e)
    {
        int[] arr = Enumerable.Range(0, 99999).ToArray();
        var sb = new StringBuilder();
        foreach (int a in arr)
        {
            sb.AppendLine(a.ToString("000000"));
           // textBox3.Text += a.ToString("000000")+Environment.NewLine;
            textBox3.Text = sb.ToString();

        }
    }

But it takes lots of time to print all the numbers.但是打印所有数字需要很多时间。

Is there any way to speed this up?有没有办法加快这个速度?

You set the text of the TextBox in each and every iteration .您在每次迭代中设置TextBox的文本。 So the textbox is redrawn 100000 times.所以文本框被重绘了 100000 次。 Of course it's slow.当然是慢了。

Move the setting of the text outside the loop:将文本的设置移到循环之外

foreach (int a in arr)
{
    sb.AppendLine(a.ToString("000000"));
}
textBox3.Text = sb.ToString();

So you only set the text when you finished composing the string and the textbox is redrawn only once.因此,您仅在完成字符串组合后才设置文本,并且文本框仅重绘一次。

May be this help可能是这个帮助

 private void button1_Click(object sender, EventArgs e)
    {
        int[] arr = Enumerable.Range(0, 99999).ToArray();
        var sb = new StringBuilder();
        foreach (int a in arr)
        {
            sb.AppendLine(a.ToString("000000"));
           // textBox3.Text += a.ToString("000000")+Environment.NewLine;

        }
         textBox3.Text = sb.ToString();
    }

How about this approach.这个方法怎么样。

    private void button1_Click(object sender, EventArgs e)
    {
        textBox3.Text = string.Join(Environment.NewLine, Enumerable.Range(0,99999).Select(x => x.ToString().PadLeft(6, '0')));
    } 

Have you tried this?你试过这个吗?

foreach (int a in arr)
{
    sb.AppendLine(a.ToString("000000"));
}
textBox3.Text = sb.ToString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM