WyldeBoyy
WyldeBoyy

Reputation: 35

Foreach loop iteration error

So I need to run a loop/loops to replace certain words existing in the entityList which appear in sentences found in the allSentencesList and then add the new sentences with the replaced words to the processedSentencesList. But the operation doesn't work as I want it to. Any idea what the error could be?

Code:

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);
            }
        }

This is what I want to display

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

This is what gets displayed

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

Upvotes: 0

Views: 78

Answers (1)

Grant Winney
Grant Winney

Reputation: 66501

Looks like you're adding to the "processed" list multiple times inside the inner foreach loop.

You want to add to the process list once, when you're done doing all the replacements you want to do in the string. Keeping your code as close to the original as possible, try this:

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

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

    processedSentencesList.Add(processedString); 
}

Upvotes: 4

Related Questions