Javatpoint Logo
Javatpoint Logo

LINQ Aggregate() Function

In LINQ, Aggregate() function is used to perform the operation on each item of the list. The Aggregate() function performs 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.

Syntax of LINQ Aggregate function in C#

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

Now we will show the example of using the linq Aggregate () function in C# to calculate the product of all the numbers in the integer array.

Syntax of LINQ Aggregate function in C#

In the above examples, there is an integer array Num. We calculated the product of all the elements present in the given array. For this, we have to specify a Lambda Expression. In the Lambda Expression, we took two input parameters, "a" and "b." And on the right-hand side, we multiply the parameters of input. Now we would be getting the product of all the numbers.

These are the steps that 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 Lambda Expression. The outcome of the first two-element (1 and 2) is stored in 'a'. Now the value of b is null.
  3. The first two elements have been used lambda will take the third element and assigned 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 (3) element. Now a and b multiplied according to lambda, and the resultant value is stored in a. Now b is set to null.
  5. The fourth element from the array is assigned to b and contains the product of the first three elements. This process will continue till the last element, and the product is finally displayed on the console.

In the same way, we are concatenating the list of items (a,b,c,d) in separated string in LINQ.

When we execute the above LINQ Aggregate () function, we will get the results as shown below:

Output

LINQ Aggregate() Function





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA