LINQ Aggregate Function with example

In LINQ, the Aggregate function is useful to perform the operations on each item of the list. The Aggregate() function will perform the action on the first and second elements and then carry forward the result. For the next operation, it will consider the previous result and the third element and then carryforwards, etc.

 

Following is the syntax of using the LINQ Aggregate() function in c# and vb.net to add all the numbers in an integer array.

Syntax of LINQ Aggregate Function in C#

int[] Num = { 1, 2, 3, 4 };
double Average = Num.Aggregate((a, b) => a + b);
Console.WriteLine("{0}", Average); //Output 10 (((1+2)+3)+4)

LINQ Aggregate Function Syntax in VB.NET

Dim Num As Integer() = {1, 2, 3, 4}
Dim Average As Double = Num.Aggregate(Function(a, b) a + b)
Console.WriteLine("{0}", Average)

The above syntax will take first two elements 1 and 2 to perform the addition and make 3 then it take previous result 3 and next element 3 and perform addition to make 6 and then add 6 to the next element 4 and result will be 10.

 

Now, we will see the examples of using the LINQ Aggregate() function in c# and vb.net to calculate the product of all the numbers in the integer array.

LINQ Aggregate() Function Example in C#

using System;
using System.Collections.Generic;
using System.Linq;

namespace Linqtutorials
{
  class Program
  {
    static void Main(string[] args)
    {
      int[] Num = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
      Console.WriteLine("Find the Product of the elements:");
      double Average = Num.Aggregate((a, b) => a * b);
      Console.WriteLine("The Product is {0}", Average); //Output 362880 ((((((((1*2)*3)*4)*5)*6)*7)*8)*9)
      string[] charlist = { "a", "b", "c", "d" };
      var concta = charlist.Aggregate((a, b) => a + ',' + b);
      Console.WriteLine("Concatenated String: {0}",concta); // Output a,b,c,d
      Console.ReadLine();
    }
  }
}

LINQ Aggregate Function Example in VB.NET 

Module Module1
Sub Main()
Dim Num As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9}
Console.WriteLine("Find the Product of the elements:")
Dim Average As Double = Num.Aggregate(Function(a, b) a * b)
Console.WriteLine("The Product is {0}", Average)
Dim charlist As String() = {"a", "b", "c", "d"}
Dim concta = charlist.Aggregate(Function(a, b) a + ","c + b)
Console.WriteLine("Concatenated String: {0}", concta)
Console.ReadLine()
End Sub
End Module

In the above examples, we have an integer array Num. We will calculate the product of all the elements present in the given array. To do this we have to specify a Lambda expression using Aggregate function. In the Lambda expression we took two input parameters "a" and "b". And on the right hand side we simply multiply the input parameters. So we would be getting the product of all the numbers. But wait, how this is possible?  We have just two input parameters and much more elements in the array. So how does Lambda work in this scenario?

 

The following steps will describe the functionality of the above example.

 

  1. The first element 1 from the array is assigned to a. The second element 2 is assigned to b.
  2. The product of the two elements is calculated using the Lambda expression. This product of the first two elements (1 and 2) is now stored in a. The value of b is now null.
  3. Since the first two elements have been used, lambda will take the third element and assign its value to b which was null.
  4. Now "a" contains the product of the first two elements (1 and 2) and b contains the third element (3). Now a and b gets multiplied according to the lambda, and the resultant value is now stored in a. Now b is set to null.
  5. The fourth element from the array gets assigned to b and a contains the product of the first three elements. This process continues until the last element and the product are displayed on the console.

Same way, we are concatenating the list of items (a,b,c,d) into comma-separated string in linq.

 

So we just saw how simple it is to calculate the product of the elements in the integer array. If one uses a normal non LINQ approach, we have to write a longer code, but here, just one line of code does the trick.

 

When we execute the above LINQ Aggregate() fuction examples, we will get the result as shown below.

 

Find the Product of the elements:

The Product is 362800

Concatenated String: a,b,c,d

This is how we can use LINQ Aggregate() function in applications to perform operations on elements in a list or collection object based on our requirements.