Where is the “Fold” LINQ Extension Method?

Deadly 提交于 2019-12-12 08:17:14

问题


I found in MSDN's Linq samples a neat method called Fold() that I want to use. Their example:

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

Unfortunately, I can't get this to compile, either in their example or in my own code, and I can't find anywhere else in MSDN (like Enumerable or Array extension methods) that mention this method. The error I get is a plain old "don't know anything about that" error:

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?)

I'm using other methods which I believe come from Linq (like Select() and Where()), and I'm "using System.Linq", so I think that's all OK.

Does this method really exist in C# 3.5, and if so, what am I doing wrong?


回答1:


You will want to use the Aggregate extension method:

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

See MSDN for more information. It lets you specify a seed and then an expression to calculate successive values.




回答2:


Fold (aka Reduce) is the standard term from functional programming. For whatever reason, it got named Aggregate in LINQ.

double product = doubles.Aggregate(1.0, (runningProduct, nextFactor) => runningProduct* nextFactor);


来源:https://stackoverflow.com/questions/1230729/where-is-the-fold-linq-extension-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!