LINQ Aggregate: The Ins and Outs in a Nutshell
Often overlooked, the Aggregate function in LINQ is a powerful tool that deserves better illumination. Let's explore its essence in a clear and concise manner.
Aggregate performs sequential operations on each element of a list, where each operation considers the results of preceding operations. In other words, it starts by operating on the first and second elements, then carries the result forward.
Example 1: Summing Numbers
Consider an array of numbers: [1, 2, 3, 4].
var nums = new[] { 1, 2, 3, 4 }; var sum = nums.Aggregate((a, b) => a + b); Console.WriteLine(sum); // Output: 10
Aggregate will calculate the sum: (1 2) 3 4 = 10. It adds subsequent elements to the running total, resulting in the final sum.
Example 2: Concatenating Strings
Next, let's create a comma-separated string from an array of characters:
var chars = new[] { "a", "b", "c", "d" }; var csv = chars.Aggregate((a, b) => a + ',' + b); Console.WriteLine(csv); // Output: a,b,c,d
In this case, Aggregate combines each character with a comma, resulting in the concatenated string.
Example 3: Multiplying Numbers with a Seed
Aggregate also offers an overload that accepts a seed value:
var multipliers = new[] { 10, 20, 30, 40 }; var multiplied = multipliers.Aggregate(5, (a, b) => a * b); Console.WriteLine(multiplied); // Output: 1200000
Starting with the seed value of 5, Aggregate multiplies each element of the array with it, resulting in the cumulative product: ((5 10) 20) 30 40 = 1200000.
In summary, Aggregate allows you to perform sequential operations on elements in a list, where each operation builds upon the preceding results. It's a versatile function that can be utilized to solve various data manipulation problems.
The above is the detailed content of How Does LINQ's Aggregate Function Work?. For more information, please follow other related articles on the PHP Chinese website!