简体   繁体   English

比较列表成字符串

[英]compare list into string

I need to check if the string on my list are found on the text to search and how many string on the list are found 我需要检查列表中的字符串是否在text to searchtext to search中找到以及列表中有多少个字符串

this is my string 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. 

this is my list 这是我的清单

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 

I created a sample code 我创建了一个示例代码

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!");
    }
}

But it prints the success three times. 但是它success打印了三遍。 it should be once only. 它应该只有一次。 How can i make this work? 我该如何工作? How can i skip the item that are already used to search the item. 如何跳过已用于搜索项目的项目。

It prints success three times because your are looping in myList . 因为您正在myList中循环,它会成功打印三遍 Try like this: 尝试这样:

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!");
}

replace 更换

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

with

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

to check item by item if it exists in your string. 检查您的字符串中是否存在逐项检查。

Your current version checks 3x if any of those items exists which is always true fore the case word 3 您当前的版本会检查3x是否存在其中的任何一项,在大小写word 3总是正确的

To get the count, you can use the following: 要获得计数,可以使用以下方法:

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)));

change for cycle to: 周期更改为:

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

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

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