嵌套的Foreach循环及其顺序

时间:2014-08-07 14:44:56

标签: c# loops foreach nested

我想知道嵌套的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循环的声明顺序是否会影响进程?

谢谢:)

2 个答案:

答案 0 :(得分:0)

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

修复应该很简单;不要遍历processedSentences,而只是遍历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
    }
}

答案 1 :(得分:0)

我认为你对foreach正在做的事情有错误的想法:

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

如果我理解正确,你的代码会以一个空列表的foreach开头。这意味着你的代码将尝试在列表中找到一个对象,这当然不存在,并且在它之后&#34;完成&#34;对于所有对象(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
    }
}