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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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[] { ' ', ',', ':' })
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0