简体   繁体   English

比较字符串列表和另一个字符串

[英]compare list of strings with another string

I have 1 long string which looks like : "item1, item7, item9" etc. Then I have a list which looks like: 我有1个长字符串,看起来像: "item1, item7, item9"等。然后,我有了一个列表,看起来像:

"item2",
"item3",
"item9"

I want to run a check to see if any of the list strings match anything within the long string. 我想检查一下列表字符串是否与长字符串中的任何内容匹配。 I could use a foreach loop, but I'm thinking there must be an easy LINQ expression which I can't seem to get right. 我可以使用一个foreach循环,但是我在想必须有一个简单的LINQ表达式,但我似乎不太正确。

You could try something like this: 您可以尝试这样的事情:

var isContained = list.Any(x=>stringValue.Contains(x));

where list is the list of strings, stringValue is the string you have. 其中list是字符串列表, stringValue是您拥有的字符串。

In the above code, we use the Any method, which looks if there is any element in the list that makes the predicate we supply to be true . 在上面的代码中,我们使用Any方法,该方法查找列表中是否有任何元素使我们提供的谓词为true The predicate has as input a list item and check if this item is contained in the stringValue . 谓词有一个列表项作为输入,并检查该项目是否包含在stringValue If so that returns true. 如果是这样,则返回true。 Otherwise false. 否则为假。

        string longString = "item1,item7,item9";
        List<string> myList=new List<string>(new string[]{"item2","item3","item9"});

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

How about: 怎么样:

// Set up the example data
String searchIn = "item1, item7, item9";
List<String> searchFor = new List<String>();
searchFor.Add("item2");
searchFor.Add("item3");
searchFor.Add("item9");

var firstMatch = searchFor.FirstOrDefault(p => { return -1 != searchIn.IndexOf(p); });
// firstMatch will contain null if no item from searchFor was found in searchIn,
// otherwise it will be a reference to the first item that was found.

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

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