C# Program to Show the Usage of LINQ Aggregate() Method


The Aggregate() method is a powerful LINQ method that allows you to perform a reduction operation on a sequence of elements. This method can be used to perform calculations on a collection of data, such as finding the sum, product, or maximum value of a set of numbers. In this article, we will explore how to use the Aggregate() method in a C# program.

What is the Aggregate() Method?

The Aggregate() method is a LINQ extension method that takes two parameters: a seed value and a function that performs a reduction operation on a sequence of elements. The seed value is the initial value of the operation, and the function specifies how to combine each element of the sequence with the previous result.

Syntax of Aggregate() Method

public static TAccumulate Aggregate<TSource, TAccumulate>(this IEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func)

Example: Using Aggregate() Method to find the Sum of a Sequence of Numbers

Let's see an example of how to use the Aggregate() method to find the sum of a sequence of numbers.

using System.IO;
using System;
using System.Linq;

class Program {
   static void Main(string[] args) {
      int[] numbers = { 1, 2, 3, 4, 5 };
   
      int sum = numbers.Aggregate((x, y) => x + y);
   
      Console.WriteLine("The sum of the sequence is: {0}", sum);
   }
}

In this code, we have an array of integers named numbers. We use the Aggregate() method to calculate the sum of the sequence by passing a lambda expression that adds the two elements together.

Output

The sum of the sequence is: 15

Example: Using Aggregate() Method to find the Product of a Sequence of Numbers

Now, let's see an example of how to use the Aggregate() method to find the product of a sequence of numbers.

using System;
using System.Linq;

class Program {
   static void Main() {
      int[] numbers = { 1, 2, 3, 4, 5 };
      int product = numbers.Aggregate(1, (x, y) => x * y);
      Console.WriteLine("The product of the sequence is: {0}", product);
   }
}

In this code, we have an array of integers named numbers. We use the Aggregate() method to calculate the product of the sequence by passing an initial value of 1 and a lambda expression that multiplies the two elements together.

Output

The product of the sequence is: 120

Conclusion

The Aggregate() method is a powerful LINQ method that can be used to perform a reduction operation on a sequence of elements. In this article, we explored how to use the Aggregate() method in a C# program to find the sum and product of a sequence of numbers.

Updated on: 04-May-2023

112 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements