I could use the following linq expression to count the number of occurrences of a word as follows:
string test = "And And And";
int j = test.Split(' ').Count(x => x.Contains("And"));
However what if I was searching for "And And", Is there a way to use linq to count words without using split. Do any of these methods take longer the O(n)?
You can use a regular expression:
string test = "And And And";
int j = Regex.Matches(test, "And").Cast<Match>().Count();
BTW, do you want to allow overlapping occurrences? i.e. if you're looking for "And And", do you consider that test
contains 1 or 2 occurrences of it?
I found a clever solution that can be resolved serverside with most LINQ to ORMs:
string search = "foo";
int searchLength = search.Length;
var result = qry.Select(i => new { Object = i, Occurrences = (i.SomeProperty.Length - i.SomeProperty.Replace(search, "").Length) / searchLength });
The idea is to replace the substring by an empty string and then divide the difference in string length by the length of the search term.
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