Aggregate

https://msdn.microsoft.com/en-us/library/bb549218(v=vs.110).aspx

public static TAccumulate Aggregate<TSource, TAccumulate>(this IEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func);

Parameters

source
Type: System.Collections.Generic.IEnumerable<TSource>

An IEnumerable<T> to aggregate over.

seed
Type: TAccumulate

The initial accumulator value.

func
Type: System.Func<TAccumulate, TSource, TAccumulate>

An accumulator function to be invoked on each element.

举例:

https://www.codewars.com/kata/beginner-reduce-but-grow/train/csharp

对数组中的元素,计算累乘

using System.Linq;

public class Kata
{
    public static int Grow(int[] x)
    {
        return x.Aggregate(1, (current, item) => current * item);
    }
}

 

求和:

return Enumerable.Range(3, n - 3 + 1).Where(x => x%3 == 0 || x%5 == 0).Aggregate(0, (current, item) => current + item);

where之后可以直接Sum

 

posted @ 2016-10-12 10:04  ChuckLu  阅读(451)  评论(0编辑  收藏  举报