2017-08-03 23 views
0

我需要检查,如果我的名单上的弦都在名单上的text to search多少串被发现对比清单到字符串

这个发现是我要搜索的字符串

What is Lorem Ipsum? 
Lorem Ipsum is simply dummy text of the printing and typesetting 
industry. Lorem Ipsum has been the industry's standard dummy 
text ever since the 1500s, when an unknown printer took a galley 
of type and scrambled it to make a type specimen book. 

这是我的名单

What is Lorem Ipsum? 
Lorem Ipsum is simply dummy text of the 
printing and typesetting 
industry. Lorem Ipsum has been the 
industry's standard dummy 
text ever since the 1500s, when 
an unknown printer took a galley 

我创建了一个示例代码

string longString = "word1, word2, word 3"; 

List<string> myList = new List<string>(new string[] { "word4", "word 2", "word 3" }); 

for (int i = 0; i < myList.Count; i++) 
{ 
    if (myList.Any(str => longString.Contains(str))) 
    { 
     Console.WriteLine("success!"); 
    } 
    else 
    { 
     Console.WriteLine("fail!"); 
    } 
} 

但它打印三次success。它应该只有一次。我怎样才能做这项工作?我如何跳过已经用于搜索项目的项目。

回答

0

变化的周期为true:

foreach (string check in myList) 
      { 
       if (longString.Any(str => longString.Contains(check))) 
       { 
        Console.WriteLine("success!"); 
       } 
       else 
       { 
        Console.WriteLine("fail!"); 
       } 
      } 
2

它打印成功三次,因为你在循环myList。 尝试这样的:

string longString = "word1, word2, word 3"; 

List<string> myList = new List<string>(new string[] { "word4", "word 2", "word 3" }); 

if (myList.Any(str => longString.Contains(str))) 
{ 
    Console.WriteLine("success!"); 
} 
else 
{ 
    Console.WriteLine("fail!"); 
} 
0

得到计数,可以使用以下命令:

string longString = "word1, word2, word 3"; 
List<string> myList = new List<string>(new string[] { "word4", "word 2", "word 3" }); 
int count = myList.Count(s => s.Any(a => longString.Contains(s))); 
2

更换

if (myList.Any(str => longString.Contains(str))) 

if (longString.Contains(myList[i])) 

通过检查项目如果它存在于你的项目中字符串。

您当前的版本检查3倍,如果任何这些项目的存在,这始终是向前的情况下word 3