任何建议将值存储在lambda表达式中

问题描述:

我正在尝试使用lambda表达式递归地编写字符串中字的计数发生的内联函数。任何建议将值存储在lambda表达式中

功能:

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; 

的问题是,我呼吁IndexOf方法两次, 第一个是递归断点条件,第二个是获取价值添加。

有没有任何建议叫它一次?

在此先感谢。

+1

对于使用正则表达式来说,它可能不工作,可能是像\ b(search_term)\ b之类的东西。我错过了什么吗? – 2010-10-24 23:16:05

+0

这是一个练习吗?你是否想做其他的事情,这是一个非代表性的样本?你想在生产代码中使用它吗? – outis 2010-10-25 04:42:48

+0

如果你还没有,给[[递归lambda表达式]](http://blogs.msdn.com/b/madst/archive/2007/05/11/recursive-lambda-expressions.aspx)一个读。 – outis 2010-10-25 10:58:44

如果你不正是另一种方式不介意你可以做的非纯功能拉姆达: -

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; 
} 
+0

什么是“非纯”的呢? (我不满意:-)它只是表明“非lambda”(例如anon-function/delegate中的多行)与“纯lambda”相比是一个完美的(如果不是更好的)方法。我相信他们都是一样的编译,但没有证实这一点。 – 2010-10-24 23:12:47

+0

pst:这是一个“非纯”的意思,它是一个lambda,你不能成为一个'表达式>' – Gabe 2010-10-24 23:16:48

+0

@Highttech:在大括号之间,就像一个委托, 然后? – IAbstract 2010-10-24 23:30:13

我建议你使它成为一个单独的方法

Func<string, string, int> getOccurrences = GetOccurrences; 

    private int GetOccurrences(string text, string searchTerm) 
    { 
     //...  
    } 

或内嵌

Func<string, string, int> getOccurrences = delegate(string text, string searchTerm) 
              { 
               //... 
              }; 

与lambda语法,但写了上

Func<string, string, int> getOccurrences = (string text, string searchTerm) => 
              { 
               //... 
              }; 

你可以做这样的:

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

你可以使用一个额外的,匿名的拉姆达并立即调用它。我不能确定确切的C#语法,但它应该是这个样子:

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

我通常解决这些类型的问题,忽略任何优化,只是删除匹配项,检查任何变化结果字符串的长度。

Func<String, String, Int32> getOccurrences = (text, term) => 
    (text.Length - text.Replace(term, "").Length)/term.Length;