将列表比较为字符串

时间:2017-08-03 05:28:34

标签: c# string list

我需要检查列表中的字符串是否在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三次。它应该只有一次。我怎样才能做到这一点?如何跳过已用于搜索项目的项目。

4 个答案:

答案 0 :(得分: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!");
}

答案 1 :(得分:2)

替换

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

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

逐项检查字符串是否存在。

如果存在任何这些项目,那么您当前的版本会检查3倍word 3

答案 2 :(得分: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)));

答案 3 :(得分:0)

将周期更改为:

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