簡體   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