繁体   English   中英

嵌套foreach循环的C#正确格式?

[英]C# Proper format of a Nested foreach loop?

我需要遍历包含字符串句子的列表,并从另一个列表中查找包含字符串词的句子,并将它们添加到单独的列表中以进行显示。 下面的代码多次打印相同的句子,所以我想知道嵌套的foreach循环的正确格式是什么?

 List<string> sentenceList = new List<string>();
        sentenceList.Add("Dog ate a bone");
        sentenceList.Add("Cat had a ball and bone");

        List<string> keywords = new List<string>();
        keywords.Add("bone");
        keywords.Add("Cat")

 List<string> NewList = new List<string>();

            foreach (string sentence in sentenceList)
            {
                foreach (string word in keywords)
                {
                    if (sentence.Contains(word))
                    {
                        NewList.Add(sentence);
                    }
                }
            }

我得到的输出是:

狗吃了骨头

猫有球和骨头

猫有球和骨头

我希望每个句子明显只出现一次,但为什么又重复两次 我究竟做错了什么?

在两个句子中,“ bone”是您的关键字列表应包含的相同单词

List<string> keywords = new List<string>();
        keywords.Add("Dog"); // or  keywords.Add("ate")
        keywords.Add("Cat")

再次添加是因为您没有检查列表中是否已经存在该sentence

您可以检查它是否已经存在,不添加它:

if (sentence.Contains(word))
{
  if(!NewList.Contains(sentence))
     NewList.Add(sentence);
}

您的代码:

foreach (string sentence in sentenceList)
{
   foreach (string word in keywords)
   {
      if (sentence.Contains(word))
      {
         if(!NewList.Contains(sentence))
            NewList.Add(sentence);
      }
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM