Reputation: 575
I have a list of words
var words = List<string> { "Apple", "Banana", "Cherry" };'
and a string
var fruitString = "Apple Orange Banana Plum";
I know if I do
var hasFruits = words.Contains(w => fruitString.Contains(w));
that I can tell if the string contains any of those words. What I need to do is tell how many of those words match.
I know that I can do
var count = 0;
foreach (var word in words)
{
if (fruitString.Contains(word))
{
count++;
}
}
but is there a way of doing this in a Linq one-liner?
Upvotes: 1
Views: 2044
Reputation: 236188
If you want to check count of words which appear in string separated by whitespaces, you can use intersection of sets:
fruitString.Split().Intersect(words).Count() // 2
If you want to check which words your string have - just remove Count call:
fruitString.Split().Intersect(words) // "Apple", "Banana"
Note1: if you do String.Contains
then "Apple"
will be found in "Applejack"
string
Note2: passing StringComparer.InvariantCultureIgnoreCase
as second argument to Intersect
method call will make ignore case string comparison and "apple" will match "Apple".
Note3: you can use Regex.Split
to get words from string which has not only white spaces between words. E.g. for something like "I look to the east and see: apple, orange and banana!"
Upvotes: 4
Reputation: 32192
Yes, simply swap Contains
for Count
:
var count = words.Count(w => fruitString.Contains(w));
Note that this retains the same result as your original code - as pointed out in Sergey's answer, this approach may be naive, depending on what you're trying to achieve.
Upvotes: 4