Home >Backend Development >C++ >How Does LINQ's Aggregate Function Work for Summation, Concatenation, and Multiplication?
The LINQ Aggregate function performs an operation on a sequence of elements while taking into account the results of previous operations. In essence, it iteratively processes each element in the sequence, accumulating the outcome of the operation.
To understand Aggregate, consider the following definitions and examples:
var nums = new[] { 1, 2, 3, 4 }; var sum = nums.Aggregate((a, b) => a + b); Console.WriteLine(sum); // Output: 10 (1 + 2 + 3 + 4)
var chars = new[] { "a", "b", "c", "d" }; var csv = chars.Aggregate((a, b) => a + "," + b); Console.WriteLine(csv); // Output: a,b,c,d
var multipliers = new[] { 10, 20, 30, 40 }; var multiplied = multipliers.Aggregate(5, (a, b) => a * b); Console.WriteLine(multiplied); // Output: 1200000 ((((5 * 10) * 20) * 30) * 40)
Example 1: Summing Numbers
var nums = new[] { 1, 2, 3, 4 }; var sum = nums.Aggregate((a, b) => a + b);
Explanation:
Example 2: Creating a CSV from Strings
var chars = new[] { "a", "b", "c", "d" }; var csv = chars.Aggregate((a, b) => a + "," + b);
Explanation:
Example 3: Multiplying Numbers with a Seed
var multipliers = new[] { 10, 20, 30, 40 }; var multiplied = multipliers.Aggregate(5, (a, b) => a * b);
Explanation:
LINQ Aggregate provides a powerful way to perform various operations on sequences, including summation, concatenation, and multiplicative accumulation. Its versatility and ease of use make it a valuable tool for data manipulation in C# and other .NET languages.
The above is the detailed content of How Does LINQ's Aggregate Function Work for Summation, Concatenation, and Multiplication?. For more information, please follow other related articles on the PHP Chinese website!