C# Program to Show the Usage of LINQ Aggregate() Method
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.
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.
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.
Please Login to comment...