# Finding the factorial for a number using Aggregate in LINQ C#

August 5, 2014 5 Comments

The Aggregate LINQ operator allows you to define your own aggregation function to be performed on a sequence. The function is performed on each element and the result of the function is passed into the next iteration. The final result of the operation is returned at the end.

To calculate the factorial of 5, i.e. 5!, we’d calculate 5x4x3x2x1 or 1x2x3x4x5, doesn’t matter. The first overload of the operator accepts a Function of int, int, int, i.e. it takes two integers and returns an integer.

Here’s how we can calculate 5!:

IEnumerable<int> ints = Enumerable.Range(1, 5); int factorial = ints.Aggregate((f, s) => f * s);

…which correctly gives 120. ‘f’ is the aggregate value and ‘s’ is the current element in the lambda expression.

The following is performed step by step:

- The first iteration passes in f = 1 and s = 2, which yields 1×2 = 2
- In the second iteration f is the result of the first iteration, i.e. 2 and s will be the second element, i.e. 3, yielding 2×3 = 6
- Then it continues with f = 6 from the second operation and taking 4 from the integer sequence, giving 6×4 = 24
- Finally we get 24×5 = 120

View the list of posts on LINQ here.

Reblogged this on Dinesh Ram Kali..

I think, in the first iteration, it is f = 1, s = 2;

Consider the following program:

IEnumerable ints = Enumerable.Range(1, 5);

int factorial = ints.Aggregate((f, s) => { Console.WriteLine(“{0}, {1}”, f, s); return f * s; } );

Output:

1, 2

2, 3

6, 4

24, 5

You’re correct, I’ll update the post.

Thanks for your input.

//Andras

It is giving the following error:

‘System.Collections.IEnumerable’ does not contain a definition for ‘Aggregate’ and no extension method ‘Aggregate’ accepting a first argument of type ‘System.Collections.IEnumerable’ could be found (are you missing a using directive or an assembly reference?)

It is giving the following Error:

‘System.Collections.IEnumerable’ does not contain a definition for ‘Aggregate’ and no extension method ‘Aggregate’ accepting a first argument of type ‘System.Collections.IEnumerable’ could be found (are you missing a using directive or an assembly reference?)