简体   繁体   中英

Count number of matches from a list words in a string

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?

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.

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. Eg for something like "I look to the east and see: apple, orange and banana!"

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