Reduce

Apply the reduction function to each element of the collection, threading an accumulator argument through the computation.

Apply the function to the first two elements of the collection.

Parameters

Returns

Func<T, T, T> reduction

IEnumerable<T> source

TState

Usage

Accumulating a sum of each element in a collection

//IEnumerable<int> source = 
//    { 4, 5, 6, 7 }

int result = source.Reduce( 
        (accumulator, element) => accumulator + element);

//result = 22

When the type of elements in your collection are: int, decimal, double, string or bool you can also use this function combined with the Operations described in operations section as folder functions.

Using an operation as a folder

//IEnumerable<int> source = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
int result = source.Fold(15, IntegerOperations.Add);

//result = 15 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
//result = 70

Last updated