The following are the types of aggregate functions:
- Min
- Max
- Count
- Sum
- Average
- Aggregate
All these functions are present in the System.Linq namespace.
Let's look at an example of each function.
Example 1
In this example we will create a console application that will give us the smallest number from an array without using LINQ and we will write the same program using LINQ.
So, let's dive right in.
In Visual Studio, I have a console application in which there is a class Program with a Main method.
In the Main method I have created an array of numbers as in the following:
From the preceding array we want to retrieve the smallest number and print it on the console window.
To print the lowest number, first we need to create a variable that will hold the value.
To store the lowest number in the LowestNumber variable, we need to find the smallest number from the ArrayOfNumbers and for that we can use a foreach loop.
We have used a foreach loop to retrieve all the numbers from the ArrayOfNumbers. After retrieving all the values, check if the nullable variable that we created does not have a value and using or(||) check if the value of n is smaller than the LowestNumber value, if any of the case is true then assign the value of n to the LowestNumber variable.
So, when the code executes, it will first check if the lowestNumber variable contains a value or not. If not then it will assign the first value of n to ArrayOfNumbers. Then again it will loop and check the same condition but now the first condition will be false because now the LowestNumber has a value. So, it will check the second condition and if the n value is smaller than the LowestNumber, then value of n will be assigned to the LowestNumber.
- using System;
-
- namespace AggregateFunctionsInLINQ {
- class Program {
- static void Main(string[] args) {
- int[] ArrayOfNumbers = { 5, 4, 6, 3, 7, 1, 3, 9 };
- int? LowestNumber = null;
-
-
- foreach(int n in ArrayOfNumbers) {
- if(!LowestNumber.HasValue || n < LowestNumber) {
- LowestNumber = n;
- }
- }
- Console.WriteLine(LowestNumber);
- }
- }
- }
Run the applicationTo get the smallest number, we must write many lines of codes. Now let's see how to do the same thing using LINQ.
To get the smallest number, we can use the Min() aggregate function.
Look at the intellisense, this function returns the minimum value in a sequence. So, using this extension method we will get the lowest value from the ArrayOfNumbers.
- using System;
- using System.Collections.Generic;
- using System.Linq;
-
- namespace SmallestNumberUsingLINQ {
- class Program {
- static void Main(string[] args) {
- int[] ArrayOfNumbers = { 5, 4, 6, 3, 7, 1, 3, 9 };
- int LowestNumber = ArrayOfNumbers.Min();
- Console.WriteLine(LowestNumber);
- }
- }
- }
Run the applicationExample 2
Let's look at another example. In this we will retrieve the largest number from ArrayOfNumbers.
In the preceding cs file, we have written the same code except we are checking if the n value is greater than the LargestNumber value. If the condition is true then we are assigning the n's value to the LargestNumber variable.
Run the applicationLet's see how to do the same thing using LINQ.
To get the minimum value from the integer of arrays, we used the Min aggregate function. To get the maximum value from the integer of arrays, we will use the Max aggregate function.
Run the applicationLet's say from the ArrayOfNumbers we want the largest even number.
Without LINQTo get the largest even number, we need to add another condition where we will check if the number returns 0 as the remainder.
Run the applicationUsing LINQTo filter the records we can use the
Where extension method.
Run the applicationExample 3 In this demo we will find the sum of all the numbers.
Without LINQRun the applicationWith LINQTo get the sum of all the numbers, we can use Sum aggregate function.
Run the applicationExample 4
In this example we will count the number elements present in ArrayOfNumbers.
Without LINQRun the applicationUsing LINQRun the applicationExample 5In this example we will see how to get the average of the ArrayOfNumbers.
Without LINQRun the applicationWith LINQTo get the average in LINQ, we can use the Average aggregate function.
Note: The return type of this function is double.
Run the application
Example 6
In this demo we will see how to use the Aggregate function.
In my console application, I have this array of Names.
- string[] Names = {"Sam","Sara","Aiden","Trevor","Michael"};
I want this separate string to be displayed as a single comma-separated string.
So. Let's see how do it.
Without LINQRun the applicationWe got the output as a single string separated by comma.
But we have a comma after the last string and we don't want a comma after the last string.
So, let's see how to remove it.
To remove a comma from the last string, we can use the LastIndexOf method.
Run the applicationWith LINQRun the application
You might be thinking, how does this Aggregate function work?
If you look at the expression
string SingleString = Names.Aggregate((a, b) => a + ", " + b);This (
a, b) expression is nothing but two parameters of type string.
When the program first executes, It will take Sam and Sara and assign it to a and b and based on the expression
a + ", " + b this aggregate function will concatenate these two values separated by a comma and assign this value back to the first parameter,
a.
Then it will take Aiden in b and will concatenate Sam, Sara and Aiden separated by commas because the parameter a holds the previous concatenated values and then again this a will hold all the three values and Trevor will be assigned to b and so on. In the end the final result will be assigned to the SingleString variable.