Calculate Product with Linq

I am learning LINQ and have a very simple question that I think will help my understand the technology better. How can I find the product of an array of ints?

For example, what is the LINQ way to do:

int[] vals = { 1, 3, 5 };
return vals[0] * vals[1] * vals[2];

1 Answer

This would work:

var product = vals.Aggregate(1, (acc, val) => acc * val);

You're starting with a seed of 1 and then the function is called for each of your values with two arguments, acc which is the current accumulated value, and val which is the value in the array; the function multiplies the current accumulated value by the value in the array and the result of that expression is passed as acc to the next function. i.e. the chain of function calls with the array you provided will be:

(1, 1) => 1
(1, 3) => 3
(3, 5) => 15
5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest