嵌套Foreach循环及其顺序

本文关键字:顺序 循环 Foreach 嵌套 | 更新日期: 2023-09-27 18:17:01

我想知道嵌套foreach循环在编程中声明的顺序是否重要?我正在运行一个嵌套的foreach循环,由于一些错误,信息没有被处理。

在这种情况下,我试图访问存储在称为allSentencesList列表中的"句子",并替换在这些句子中发现的某些"单词",这些句子也存在于称为entityList (XmlNode类型)的列表中,然后最后将它们添加到称为processedSentencesList的列表中。

foreach (string processedSentence in processedSentencesList) //list that needs adding
{
    foreach (XmlNode entity in entityList) //xmlnode list containing two xml tags: text and type 
    {
        foreach (string sentence in allSentencesList) //list containing sentences
        {
            string processedString = sentence.Replace((entity["text"].InnerText), 
                (entity["text"].InnerText + "/" + entity["type"].InnerText)); //replacing the words found in the 'text' tag with the aforementioned new word 
            processedSentencesList.Add(processedString); //adding the new sentence to the new list
        }
    }
}

然而,被替换单词的处理句子没有添加到新的列表中,因此让我想知道嵌套foreach循环的声明顺序是否会影响进程?

谢谢你

嵌套Foreach循环及其顺序

我假设您的processedSentences集合一开始是空的。因此,循环永远不会被执行。除此之外,你不应该在迭代一个集合时修改它。

修复应该很简单;不遍历processsedsentence,而只遍历entityList:

var processedSentencesList = new List<string>();
foreach (XmlNode entity in entityList) //xmlnode list containing two xml tags: text and type 
{
    foreach (string sentence in allSentencesList) //list containing sentences
    {
        string processedString = sentence.Replace((entity["text"].InnerText), 
            (entity["text"].InnerText + "/" + entity["type"].InnerText)); //replacing the words found in the 'text' tag with the aforementioned new word 
        processedSentencesList.Add(processedString); //adding the new sentence to the new list
    }
}

我想你对foreach在做什么有错误的想法:

foreach语句获取list'array'任何其他对象组中的每个对象,并对每个对象执行操作。

如果我理解正确的话,您的代码以一个an foreach开始,用于一个空列表。这意味着你的代码将尝试在列表中找到一个对象,当然这个对象并不存在,并且在它"完成"所有对象之后(AKA没有做任何事情),它将跳过整个循环。

所做的需要做的是对现有的两个列表(或其他)进行迭代,并在每次迭代时向列表添加processedString。请注意,有比使用XmlNodes更好的方法来替换单词,但我将使用您的代码:

foreach (string sentence in allSentencesList) //for each string in the list do as following:
{
    foreach (XmlNode entity in entityList) //Replace each word in the string:
    {
        string processedString = sentence.Replace((entity["text"].InnerText), 
            (entity["text"].InnerText + "/" + entity["type"].InnerText)); //replacing the words found in the 'text' tag with the aforementioned new word 
        processedSentencesList.Add(processedString); //adding the new sentence to the new list
    }
}