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.
Syntax:
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.
C#
using System;
using System.Linq;
class GFG{
static public void Main()
{
String[] arr = { "GeeksforGeeks" , "Java" , "C#" , "C++" , "C" };
String str = arr.Aggregate((string1, string2) => string1 +
" : " + string2);
Console.WriteLine(str);
}
}
|
Output
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.
C#
using System;
using System.Linq;
class GFG{
static public void Main()
{
int [] arr = { 5, 2, 10, 20, 5 };
int product = arr.Aggregate((num1, num2) => num1 * num2);
Console.WriteLine(product);
}
}
|
Last Updated :
26 Jan, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...