简体   繁体   中英

How to find if a string contains any items of an List of strings?

I have a string and a List of strings:

string motherString = "John Jake Timmy Martha Stewart";

and I want to find if that string contains any of the strings in a list ie:

var children = new List<string>{"John", "Mike", "Frank"};

So I want to find out if motherString contains one of the items from children ie. 'John'

What would be the best way of going about this?

The simplest code I could come up with would be:

var hasAny = children.Any(motherString.Contains);

If you expect each of the words to be seperated by a space then you could use this:

var hasAny = motherString.Split(new[] { ' ' }).Any(children.Contains);

If the words in motherString could be seperated by other characters, you could add them like this:

motherString.Split(new[] { ' ', ',', ':' })

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