[英]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? 但是有没有办法在Linq单缸纸上做到这一点?
Yes, simply swap Contains
for Count
: 是的,只需将
Contains
换为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. 请注意,这保留了与原始代码相同的结果-正如Sergey的答案所指出的 ,根据您要实现的目标,这种方法可能是幼稚的。
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: 如果要检查字符串中包含哪些单词,只需删除Count调用即可:
fruitString.Split().Intersect(words) // "Apple", "Banana"
Note1: if you do String.Contains
then "Apple"
will be found in "Applejack"
string 注意1:如果您使用
String.Contains
则在"Applejack"
字符串中将找到"Apple"
Note2: passing StringComparer.InvariantCultureIgnoreCase
as second argument to Intersect
method call will make ignore case string comparison and "apple" will match "Apple". 注意2:传递
StringComparer.InvariantCultureIgnoreCase
作为Intersect
方法调用的第二个参数将忽略大小写字符串比较,“ apple”将匹配“ Apple”。
Note3: you can use Regex.Split
to get words from string which has not only white spaces between words. 注意3:您可以使用
Regex.Split
从字符串中获取单词,而单词之间不仅只有空格。 Eg for something like "I look to the east and see: apple, orange and banana!"
例如,类似
"I look to the east and see: apple, orange and banana!"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.