I have a
List<string> words = new List<string> {"word1", "word2", "word3"};
And i want to check using linq if my string contains ANY of these words; Smthng like:
var q = myText.ContainsAny(words);
And the second, if i have a list of sentences too:
List<string> sentences = new List<string> { "sentence1 word1" , "sentence2 word2" , "sentence3 word3"};
and also neet to check if any of these sentence contains any of these words!
var q = sentences.Where(s=>words.Any(s.text))....
Using String.contains() method for each substring. You can terminate the loop on the first match of the substring, or create a utility function that returns true if the specified string contains any of the substrings from the specified list.
You can use the PHP strpos() function to check whether a string contains a specific word or not. The strpos() function returns the position of the first occurrence of a substring in a string. If the substring is not found it returns false . Also note that string positions start at 0, and not 1.
Python Find String in List using count() We can also use count() function to get the number of occurrences of a string in the list. If its output is 0, then it means that string is not present in the list. l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C'] s = 'A' count = l1.
You can use a simple LINQ query, if all you need is to check for substrings:
var q = words.Any(w => myText.Contains(w)); // returns true if myText == "This password1 is weak";
If you want to check for whole words, you can use a regular expression:
Matching against a regular expression that is the disjunction of all the words:
// you may need to call ToArray if you're not on .NET 4 var escapedWords = words.Select(w => @"\b" + Regex.Escape(w) + @"\b"); // the following line builds a regex similar to: (word1)|(word2)|(word3) var pattern = new Regex("(" + string.Join(")|(", escapedWords) + ")"); var q = pattern.IsMatch(myText);
Splitting the string into words with a regular expression, and testing for membership on the words collection (this will get faster if you use make words into a HashSet
instead of a List
):
var pattern = new Regex(@"\W"); var q = pattern.Split(myText).Any(w => words.Contains(w));
In order to filter a collection of sentences according to this criterion all you have to do is put it into a function and call Where
:
// Given: // bool HasThoseWords(string sentence) { blah } var q = sentences.Where(HasThoseWords);
Or put it in a lambda:
var q = sentences.Where(s => Regex.Split(myText, @"\W").Any(w => words.Contains(w)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With