简体   繁体   中英

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:

"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.

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.

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 . The predicate has as input a list item and check if this item is contained in the stringValue . If so that returns 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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