MSDN의 Linq 샘플 에서 사용하려는 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에 존재합니까? 그렇다면 내가 뭘 잘못하고 있습니까?
답변
Aggregate
확장 방법 을 사용하는 것이 좋습니다 .
double product = doubles.Aggregate(1.0, (prod, next) => prod * next);
자세한 내용은 MSDN 을 참조하십시오. a를 지정한 seed
다음 식을 지정하여 연속 값을 계산할 수 있습니다.