我发现在 MSDN的LINQ的样品的被叫整齐方法倍(),我想用。他们的示例:

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

不幸的是,我不能让这个编译,无论是在他们的榜样或者我自己的代码,并在MSDN我无法找到其他地方(如可枚举或阵列扩展方法)提及此方法。我得到的错误是一个普通的老“不知道呢”错误:

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的(如选择()和Where()),我“使用System.Linq的”,所以我认为这是一切OK了。

请问这个方法确实存在,在C#3.5,如果是的话,我究竟做错了什么?

有帮助吗?

解决方案

您将要使用的Aggregate扩展方法:

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

请参阅 MSDN 获得更多的信息。它可以让你指定一个seed然后的表达式来计算连续的值。

其他提示

折叠(又名减少)是从函数编程的标准术语。无论出于何种原因,它得到了一个名为聚集在 LINQ。

double product = doubles.Aggregate(1.0, (runningProduct, nextFactor) => runningProduct* nextFactor);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top