我在 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/