C# – Check if a string contains a list of substrings and save the matching ones

c++containsstring

This is my situation: I have a string representing a text

string myText = "Text to analyze for words, bar, foo";   

And a list of words to search for in it

List<string> words = new List<string> {"foo", "bar", "xyz"};

I'd want to know the most efficient method, if exists, to get the list of the words contained in the text, something like that:

List<string> matches = myText.findWords(words)

Best Solution

There is no special analysis in this query except you have to use Contains method. So you may try this:

string myText = "Text to analyze for words, bar, foo";

List<string> words = new List<string> { "foo", "bar", "xyz" };

var result = words.Where(i => myText.Contains(i)).ToList();
//result: bar, foo