Foreach循环迭代错误

时间:2014-08-08 02:25:45

标签: c# loops foreach

所以我需要运行一个循环/循环来替换entityList中存在的某些单词,这些单词出现在allSentencesList中找到的句子中,然后将带有替换单词的新句子添加到processedSentencesList。但是操作并不像我想要的那样有效。知道错误是什么吗?

  • testBox是UI中的列表框
  • button1是UI中唯一可用的按钮

代码:

private void button1_Click(object sender, EventArgs e)
        {

            List<string> allSentencesList = new List<string>(new String[] 
            {"Cat jumped over the Wall", "Car was parked", "Car crashed" , 
                "Cat walked on the wall"});

            List<string> processedSentencesList = new List<string>();


            List<string> entityList = new List<string>(new string[] 
            { "Cat", "Car", "Wall" });


            foreach (string sentence in allSentencesList)
            {
                foreach (string entity in entityList) 
                {
                    string processedString = sentence.Replace(entity, 
                        (entity + "/" + "TYPE")); 
                    processedSentencesList.Add(processedString); 
                }
            }


            foreach (string sen in processedSentencesList)
            {
                testBox.Items.Add(sen);
                Console.WriteLine(sen);
            }
        }

这就是我要展示的内容

Cat/TYPE jumped over the Wall/TYPE
Car/TYPE was parked
Car/TYPE crashed
Cat/TYPE walked on the wall/TYPE

这是显示的内容

Cat/TYPE jumped over the Wall
Cat jumped over the Wall
Cat jumped over the Wall/TYPE
Car was parked
Car/TYPE was parked
Car was parked
Car crashed
Car/TYPE crashed
Car crashed
Cat/TYPE walked on the Wall
Cat walked on the Wall
Cat walked on the Wall

1 个答案:

答案 0 :(得分:4)

看起来你在内部foreach循环中多次添加到“已处理”列表。

当您完成要在字符串中执行的所有替换时,您希望添加到进程列表一次。保持代码尽可能接近原始代码,试试这个:

foreach (string sentence in allSentencesList)
{
    string processedString = sentence;

    foreach (string entity in entityList) 
        processedString = processedString.Replace(entity, (entity + "/" + "TYPE"));

    processedSentencesList.Add(processedString); 
}