Search code examples
c#lambdainline-code

Any suggest to store a value in a lambda expression


I'm trying to write an in-line function for count occurrences of a word in a string using lambda expressions recursively.

The function:

Func<string, string, int> getOccurrences = null;
getOccurrences = (text, searchTerm) =>
  text.IndexOf(searchTerm, StringComparison.OrdinalIgnoreCase) == -1
  ? 0
  : getOccurrences(
      text.Substring(
        text.IndexOf(searchTerm, StringComparison.OrdinalIgnoreCase)
        + searchTerm.Length),
      searchTerm) + 1;

The problem is that I'm call IndexOf method twice, The first one is for recursive break condition and the second one is to get the value for add it.

Is there any suggest to call it once?

Thanks in advance.


Solution

  • If you don't mind a non-pure-function lambda you can do:-

    Func<string, string, int> getOccurrences = null;
    getOccurrences = (text, searchTerm) => 
    {
       int i = text.IndexOf(searchTerm, StringComparison.OrdinalIgnoreCase);
       return i == -1 ? 0 : getOccurrences(i + searchTerm.Length), searchTerm) + 1;
    }