LINQ Aggregate Methods in C#
LINQ Aggregate methods help in various common calculations like getting average, count, sum etc of values in a collection. In C#, we have 6 LINQ Aggregate methods.
Min(): LINQ Aggregate Min method will give us lowest value in a collection.
Max(): LINQ Aggregate Max method will give us highest value in a collection.
Average(): LINQ Aggregate Average method will give us average of values in a collection.
Sum(): LINQ Aggregate Sum method will give us some of values in a collection.
Count(): LINQ Aggregate Count method will give us total number of items in a collection.
Aggregate(): This method is very useful, but quite tricky to understand. This method works in a looping manner and perform the calculation. This will take a delegate-based query as a parameter in the form of Lambda Expression. Aggregate method can be better understood with an example. Suppose you have 5 integer values in a collection and now you want to multiply them with each other in a sequence in which they have been placed. In such scenario, aggregate method will take first 2 values and multiply them and get the result. Now, it will take the result and multiply it with 3rd value and get the new result. This process will be keep going on until it multiplies with the last value in the sequence and get the final result.
LINQ Aggregate Example is given below.
using System; using System.Linq; namespace Hello_World { class Program { static void Main(string[] args) { int[] numbers = { 10, 16, 19, 20, 21 }; string[] names = {"Robert", "Mark", "Rony", "Peter", "Jack"}; //Getting Min Value Console.WriteLine("Min Value: " + numbers.Min()); //Getting Max Value Console.WriteLine("Max Value: " + numbers.Max()); //Getting Average Value Console.WriteLine("Average Value: " + numbers.Average()); //Getting Sum Value Console.WriteLine("Sum Value: " + numbers.Sum()); //Getting Count Console.WriteLine("Count: " + numbers.Count()); //Getting Aggregate Value Console.WriteLine("Aggregate Value: " + numbers.Aggregate((x, y) => x * y)); //Getting Comma Separated string of names. Console.WriteLine("Aggregate Value: " + names.Aggregate((x, y) => x + ", "+ y)); } } }