Using Aggregate Function on Arrays in C#

If you have got an array of integers and you want to multiple the values inside the array and display its value without using for loop  , here’s one of the ways to achieve it using the LINQ and Lambda expression .

Assuming the array of integer has the following values

int[] marks = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

You can multiply each of the values inside the integer array without using any for loop or foreach with the below code.

var aggregate = marks.Aggregate((a, b) => a * b);

Make sure you include the namespace to get it working :)

using System.Linq;
int[] marks = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

var aggregate = marks.Aggregate((a, b) => a * b);

MessageBox.Show(aggregate.ToString());
If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Leave a Reply