C# “折叠”LINQ 扩展方法在哪里?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1230729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 13:59:06  来源:igfitidea点击:

Where is the "Fold" LINQ Extension Method?

c#linqextension-methodsreduce

提问by Ken

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

我在MSDN 的 Linq 示例中发现了一个名为 Fold() 的简洁方法,我想使用它。他们的例子:

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:

不幸的是,无论是在他们的示例中还是在我自己的代码中,我都无法编译它,而且我在 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?)

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.

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

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

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

采纳答案by Jason

You will want to use the Aggregateextension method:

您将要使用Aggregate扩展方法:

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

See MSDNfor more information. It lets you specify a seedand then an expression to calculate successive values.

有关更多信息,请参阅MSDN。它允许您指定一个seed然后一个表达式来计算连续值。

回答by Richard Berg

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

折叠(又名 Reduce)是函数式编程的标准术语。无论出于何种原因,它在 LINQ 中被命名为Aggregate

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