The Aggregate() method is a powerful LINQ method that allows you to perform reduction operations on a sequence of elements. This method can be used to perform calculations on a set of data, such as finding the sum, product, or maximum of a set of numbers. In this article, we will explore how to use the Aggregate() method in a C# program.
The Aggregate() method is a LINQ extension method that takes two parameters: a seed value and a function that performs a reduction operation on the sequence of elements. The seed value is the initial value for the operation, and the function specifies how to combine each element in the sequence with the previous result.
public static TAccumulate Aggregate<TSource, TAccumulate>(this IEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> func)
Let's look at an example of using the Aggregate() method to find the sum of a series of numbers.
using System.IO; using System; using System.Linq; class Program { static void Main(string[] args) { int[] numbers = { 1, 2, 3, 4, 5 }; int sum = numbers.Aggregate((x, y) => x + y); Console.WriteLine("The sum of the sequence is: {0}", sum); } }
In this code, we have an array of integers called numbers. We use the Aggregate() method to calculate the sum of a sequence by passing a lambda expression to add two elements.
The sum of the sequence is: 15
Now, let us look at an example of how to find the product of a sequence of numbers using the Aggregate() method.
using System; using System.Linq; class Program { static void Main() { int[] numbers = { 1, 2, 3, 4, 5 }; int product = numbers.Aggregate(1, (x, y) => x * y); Console.WriteLine("The product of the sequence is: {0}", product); } }
In this code, we have an array of integers called numbers. We use the Aggregate() method to calculate the product of a sequence by passing an initial value of 1 and a lambda expression to multiply the two elements.
The product of the sequence is: 120
The Aggregate() method is a powerful LINQ method that can be used to perform reduction operations on a sequence of elements. In this article, we explored how to use the Aggregate() method in a C# program to find the sum and product of a series of numbers.
The above is the detailed content of C# program showing usage of LINQ Aggregate() method. For more information, please follow other related articles on the PHP Chinese website!