Skip to content
Related Articles
Open in App
Not now

Related Articles

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

Improve Article
Save Article
  • Last Updated : 26 Jan, 2022
Improve Article
Save Article

In LINQ, the aggregation function is the function that serves the purpose of calculating one value from a collection of values. Or we can say that the Aggregate() method is used to perform aggregation operations on the values of a collection. In simple words, the Aggregate() method implements a number of operations for each of the elements in the given collection by keeping the track of the actions that have been done before. For example, the aggregation function is used to calculate the annual rainfall that occurred in 2021 in step with readings collected the entire year. Another example, the product function is used to calculate the product of the values specified in an array.

Syntax:

result = collection.Aggregate((element1, element2) => element1 operation element2);

Here, element1 and element2 point to the two consecutive elements of the collection, the operation is the operation that we want to apply across collection values, and result stores the final answer after applying operations.

Example 1: In this program, we have initialized an array of strings and we want to place colon surrounded by whitespace (” : “) between all the elements and then combine all strings with the help of the Linq Aggregate() method.

C#




// C# program to demonstrate the working of link
// Aggregate() method
using System;
using System.Linq;
  
class GFG{
  
static public void Main()
{
      
      // Initializing an array of strings
      String[] arr = { "GeeksforGeeks", "Java", "C#", "C++", "C" };
  
      // Placing colon using Aggregate() method
    String str = arr.Aggregate((string1, string2) => string1 + 
                               " : " + string2);
  
      // Print
    Console.WriteLine(str);
}
}


Output

GeeksforGeeks : Java : C# : C++ : C

Example 2: In this program, we have initialized an array arr of integers and we are calculating the product of arr elements. Here, we have used the asterisk operator between the elements.

C#




// C# program to demonstrate the working of
// link Aggregate() method
using System;
using System.Linq;
  
class GFG{
  
static public void Main()
{
      
      // Initializing an array of strings
      int[] arr = { 5, 2, 10, 20, 5 };
  
      // Calculating product of arr elements
      // using Aggregate() method
    int product = arr.Aggregate((num1, num2) => num1 * num2);
  
      // Print the product
    Console.WriteLine(product);
}
}


Output

10000

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!