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

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:

  1. The first iteration passes in f = 1 and s = 2, which yields 1×2 = 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
  3. Then it continues with f = 6 from the second operation and taking 4 from the integer sequence, giving 6×4 = 24
  4. Finally we get 24×5 = 120

View the list of posts on LINQ here.

Advertisement
Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: