Home > Backend Development > C++ > How Does LINQ's Aggregate Function Work?

How Does LINQ's Aggregate Function Work?

Patricia Arquette
Release: 2025-01-04 18:57:44
Original
630 people have browsed it

How Does LINQ's Aggregate Function Work?

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
Copy after login

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
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template