Foreach循环迭代错误

本文关键字:错误 迭代 循环 Foreach | 更新日期: 2023-09-27 18:17:06

所以我需要运行一个循环/循环来替换存在于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

Foreach循环迭代错误

看起来你在内部foreach循环中多次添加"processed"列表。

当你完成所有你想在字符串中做的替换时,你想要添加到进程列表一次。让你的代码尽可能接近原始代码,试着这样做:

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