I need to count word by LINQ. Here is the code i use to count words in long string array but this not very efficient:
public static int WordCount(string haystack, string needle)
{
if (needle == null)
{
return 0;
}
string[] source = haystack.Split(new char[] { '.', '?', '!', ' ', ';', ':', ',', '*', '-' }, StringSplitOptions.RemoveEmptyEntries);
var matchQuery = from word in source
where word.ToLowerInvariant() == needle.ToLowerInvariant()
select word;
int count=matchQuery.Count();
return count;
}
Suppose i have a string like this:
Geo Prism GEO 1995 GEO* - ABS #16213899 HGEO-
If i try to find GEO in the above sentence, my routine doesn’t return the right count: I’d expect 4.
What’s wrong with my routine ?
You can have it as one-liner with LINQ:
Result: