【问题标题】:Foreach loop iteration errorForeach 循环迭代错误
【发布时间】:2014-08-08 02:25:44
【问题描述】:

所以我需要运行一个循环/循环来替换实体列表中存在的某些单词,这些单词出现在 allSentencesList 中的句子中,然后将带有替换单词的新句子添加到处理的句子列表中。但是该操作无法按我的意愿进行。知道错误可能是什么吗?

  • 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

【问题讨论】:

  • 请澄清与您的期望不符的地方 - 您获得更多结果的事实,或者您是否希望每个句子都发生所有替换。

标签: c# loops foreach


【解决方案1】:

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

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

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

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

    processedSentencesList.Add(processedString); 
}

【讨论】:

  • +1。这很可能是对问题的解释。
猜你喜欢
  • 2013-11-19
  • 1970-01-01
  • 2015-02-16
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 2013-03-23
  • 2018-11-18
相关资源
最近更新 更多