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.
The above syntax will take first two elements
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
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.
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
"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.
1from the array is assigned to
a. The second element
2is assigned to
2) is now stored in
a. The value of
bis now null.
bwhich was null.
"a"contains the product of the first two elements (
bcontains the third element (
bgets multiplied according to the lambda, and the resultant value is now stored in
bis set to null.
acontains 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 (
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.
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.