c# - "Fold"LINQ 扩展方法在哪里?

标签 c# linq extension-methods reduce

我在 MSDN's Linq samples 中找到我想使用一个名为 Fold() 的简洁方法。他们的例子:

double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 }; 
double product = 
     doubles.Fold((runningProduct, nextFactor) => runningProduct * nextFactor); 

不幸的是,无论是在他们的示例中还是在我自己的代码中,我都无法对其进行编译,而且我在 MSDN 中找不到其他任何地方(例如 Enumerable 或 Array 扩展方法)提及此方法。我得到的错误是一个普通的“对此一无所知”错误:

error CS1061: 'System.Array' does not contain a definition for 'Fold' and no 
extension method 'Fold' accepting a first argument of type 'System.Array' could 
be found (are you missing a using directive or an assembly reference?)

我正在使用我认为来自 Linq 的其他方法(如 Select() 和 Where()),并且我正在“使用 System.Linq”,所以我认为这一切都可以。

这个方法真的存在于 C# 3.5 中吗?如果存在,我做错了什么?

最佳答案

您将要使用聚合 扩展方法:

double product = doubles.Aggregate(1.0, (prod, next) => prod * next);

参见 MSDN了解更多信息。它允许您指定一个种子,然后指定一个表达式来计算连续的值。

关于c# - "Fold"LINQ 扩展方法在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1230729/

相关文章:

c# - GetProcessesByName 不起作用

c# - 如何用反射调用List<T>的扩展方法 "ElementAt"?

c# - VB 2008 程序集中的扩展方法不能在 C# 项目中使用?

c# - C# 中需要正则表达式来确定多个单词是否在 N 个单词中

c# - 道格拉斯-普克算法 : understanding use with polgyons

c# - 非泛型 AsEnumerable

c# - EF LINQ to SQL,除以零错误,生成的查询将参数置于错误的顺序

c# - 扩展方法无法实现 ToString

c# - 发布到 ReCAPTCHA

c# - 查询和映射复杂对象