Foreach循环不起作用

时间:2011-08-08 17:33:52

标签: c# loops foreach

我有2个foreach循环,它们都是自己工作的(当另一个被注释掉时)..但是当我把它们粘在一起时,只有第一个工作....

// Splits the RichTextBox up so the numbers can be formatted properly.
String[] myXLines = calculateXRichTextBox.Text.Split('\n');
String[] myYLines = calculateYRichTextBox.Text.Split('\n');

// Converts the numbers to only contain 2 decimal places.
foreach (string decimalXLines in myXLines)
   removedXDecimalRichTextBox.AppendText(Math.Round(Convert.ToDouble(decimalXLines), 2) + "\n");

foreach (string decimalYLines in myYLines)
   removedYDecimalRichTextBox.AppendText(Math.Round(Convert.ToDouble(decimalYLines), 2) + "\n");

是否有人知道如何使其工作或为什么它无法正常工作(RTB不附加文本)?

提前感谢您的帮助。

修改

    private void calculateXAndYPlacementOne()
    {
        try
        {
            try
            {
                // Save the contents of the placementOneListBox into the file.
                System.IO.StreamWriter sw = new System.IO.StreamWriter(filePath + "\\Calculating X,Y File.txt");

                foreach (object item in placementOneListBox.Items)
                    sw.WriteLine(item.ToString());

                sw.Close();
            }

            // Catches an exception if the file was not saved.
            catch (Exception)
            {
                MessageBox.Show("Could not write to file.");
            }

            // Reads the lines in the file to format.
            var fileReader = File.OpenText(filePath + "\\Calculating X,Y File.txt");

            // Creates a list for the lines to be stored in.
            var fileList = new List<string>();

            // Adds each line in the file to the list.
            var fileLines = "";
            while ((fileLines = fileReader.ReadLine()) != null)
                fileList.Add(fileLines);

            // Creates new lists to hold certain matches for each list.
            var xyResult = new List<string>();
            var xResult = new List<string>();
            var yResult = new List<string>();

            // Iterate over each line in the file and extract the x and y values
            fileList.ForEach(line =>
            {
                Match xyMatch = Regex.Match(line, @"(?<x>-?\d+\.\d+)\s+(?<y>-?\d+\.\d+)");
                if (xyMatch.Success)
                {
                    // Grab the x and y values from the regular expression match
                    String xValue = xyMatch.Groups["x"].Value;
                    String yValue = xyMatch.Groups["y"].Value;

                    // Add these two values, separated by a space, to the "xyResult" list.
                    xyResult.Add(String.Join(" ", new[] { xValue, yValue }));

                    // Add the results to the lists.
                    xResult.Add(xValue);
                    yResult.Add(yValue);

                    // Store the old X and Y values.
                    oldXRichTextBox.AppendText(xValue + "\n");
                    oldYRichTextBox.AppendText(yValue + "\n");
                    try
                    {
                        // Calculate the X & Y values (including the x & y displacements)
                        double doubleX = double.Parse(xValue);
                        double doubleXValue = double.Parse(xDisplacementTextBox.Text);
                        StringBuilder sbX = new StringBuilder();

                        sbX.AppendLine((doubleX + doubleXValue).ToString());

                        double doubleY = double.Parse(yValue);
                        double doubleYValue = double.Parse(yDisplacementTextBox.Text);
                        StringBuilder sbY = new StringBuilder();

                        sbY.AppendLine((doubleY + doubleYValue).ToString());

                        calculateXRichTextBox.AppendText(sbX + "");
                        calculateYRichTextBox.AppendText(sbY + "");

                        // Removes the blank lines.
                        calculateXRichTextBox.Text = Regex.Replace(calculateXRichTextBox.Text, @"^\s*$(\n|\r|\r\n)", "", RegexOptions.Multiline);
                        calculateYRichTextBox.Text = Regex.Replace(calculateYRichTextBox.Text, @"^\s*$(\n|\r|\r\n)", "", RegexOptions.Multiline);

                    }

                    // Catches if it fails
                    catch (Exception)
                    {
                        MessageBox.Show("Could not calculate the X & Y values.");
                    }
                }
            });

            // Splits the RichTextBox up so the numbers can be formatted properly.
            String[] myXLines = calculateXRichTextBox.Text.Split('\n');
            String[] myYLines = calculateYRichTextBox.Text.Split('\n');

            foreach (string decimalXLines in myXLines)
                removedXDecimalRichTextBox.AppendText(Math.Round(Convert.ToDouble(decimalXLines), 2) + "\n");

            foreach (string decimalYLines in myYLines)
                removedYDecimalRichTextBox.AppendText(Math.Round(Convert.ToDouble(decimalYLines), 2) + "\n");


            for (int theLine = 0; theLine < placementOneListBox.Items.Count; theLine++)
            {
                string replacement1 = calculateXRichTextBox.Lines[theLine];
                while (replacement1.Length < 7)
                    replacement1 = " " + replacement1;

                placementOneListBox.Items[theLine] = ((string)placementOneListBox.Items[theLine]).Remove(20, 7).Insert(20, replacement1);

                string replacement2 = calculateYRichTextBox.Lines[theLine];
                while (replacement2.Length < 7)
                    replacement2 = " " + replacement2;

                placementOneListBox.Items[theLine] = ((string)placementOneListBox.Items[theLine]).Remove(29, 7).Insert(29, replacement2);

            };
        }

        catch (Exception)
        {
            MessageBox.Show("Could not manipulate the data properly.");
        }

        File.Delete(filePath + "\\Calculating X,Y File.txt");
    }

请参阅以下答案以查看修复程序的代码

3 个答案:

答案 0 :(得分:1)

如果将每个语句分成多个语句会发生什么?你正在使用AppendText()调用内联转换Convert.ToDouble()和Round()。你确定每一步都表现得正确吗?

答案 1 :(得分:1)

输入数据中的问题,每当输入字符串不正确时,Math.Round(Convert.ToDouble(decimalXLines),2)的调用都会抛出异常。如果该代码在后台线程中工作,则不会收到严重的异常。

在我看来,String []的最后一个元素myXLines = calculateXRichTextBox.Text.Split('\ n');是一个空字符串。

您可以尝试将StringSplitOptions.RemoveEmptyEntries添加到拆分代码中:

String[] myXLines = calculateXRichTextBox.Text.Split(new []{'\n'},  StringSplitOptions.RemoveEmptyEntries);

但这是解决方法,而不是100%令人担忧的解决方案。

答案 2 :(得分:0)

我通过用以下代码替换原始代码来解决问题:

            // Splits the RichTextBox up so the numbers can be formatted properly.
            String[] myXLines = calculateXRichTextBox.Text.Split('\n');
            String[] myYLines = calculateYRichTextBox.Text.Split('\n');
            int counterX = 0;
            int counterY = 0;

            foreach (string decimalXLines in myXLines)
            {
                if (counterX == 0)
                    removedXDecimalRichTextBox.AppendText(Math.Round(Convert.ToDouble(decimalXLines), 2) + "");

                if (decimalXLines != "" && counterX != 0)
                {
                    removedXDecimalRichTextBox.AppendText("\n");
                    removedXDecimalRichTextBox.AppendText(Math.Round(Convert.ToDouble(decimalXLines), 2) + "");
                }

                counterX++;
            }

            foreach (string decimalYLines in myYLines)
            {
                if (counterY == 0)
                    removedYDecimalRichTextBox.AppendText(Math.Round(Convert.ToDouble(decimalYLines), 2) + "");

                if (decimalYLines != "" && counterY != 0)
                {
                    removedYDecimalRichTextBox.AppendText("\n");
                    removedYDecimalRichTextBox.AppendText(Math.Round(Convert.ToDouble(decimalYLines), 2) + "");
                }

                counterY++;
            }
相关问题