LINQ – Aggregate with C# Programming Example – Programming, Pseudocode Example, C# Programming Example
C# C# LINQ Examples Linq

LINQ – Aggregate with C# Programming Example

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.

Example 1:

Example 2:

Example 3:

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:

Product of the element:
Product is 362880
the Concatenated String: a,b,c,d

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: