Aggregate Function in LINQ

The following are the types of aggregate functions:

  1. Min
  2. Max
  3. Count
  4. Sum
  5. Average
  6. 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:

main method

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.

order to print

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.

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.

  1. using System;  
  2.   
  3. namespace AggregateFunctionsInLINQ {  
  4.    class Program {  
  5.       static void Main(string[] args) {  
  6.          int[] ArrayOfNumbers = { 5, 4, 6, 3, 7, 1, 3, 9 };  
  7.          int? LowestNumber = null;  
  8.   
  9.   
  10.          foreach(int n in ArrayOfNumbers) {  
  11.             if(!LowestNumber.HasValue || n < LowestNumber) {  
  12.                LowestNumber = n;  
  13.             }  
  14.          }  
  15.          Console.WriteLine(LowestNumber);  
  16.       }  
  17.    }  
  18. }  
Run the application

Run the application

To 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.

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.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4.   
  5. namespace SmallestNumberUsingLINQ {  
  6.    class Program {  
  7.       static void Main(string[] args) {  
  8.          int[] ArrayOfNumbers = { 5, 4, 6, 3, 7, 1, 3, 9 };  
  9.          int LowestNumber = ArrayOfNumbers.Min();  
  10.          Console.WriteLine(LowestNumber);  
  11.       }  
  12.    }  
  13. }  
Run the application

Run

Example 2

Let's look at another example. In this we will retrieve the largest number from ArrayOfNumbers.

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 application

application

Let'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.

Max aggregate function

Run the application

Run application

Let's say from the ArrayOfNumbers we want the largest even number.

Without LINQ

To get the largest even number, we need to add another condition where we will check if the number returns 0 as the remainder.

remainder

Run the application

largest even number

Using LINQ

To filter the records we can use the Where extension method.

Using LINQ

Run the application

Where

Example 3

In this demo we will find the sum of all the numbers.

Without LINQ

Without LINQ

Run the application

sum of all the numbers

With LINQ

To get the sum of all the numbers, we can use Sum aggregate function.

With LINQ

Run the application

Sum aggregate function

Example 4

In this example we will count the number elements present in ArrayOfNumbers.

Without LINQ

count the number

Run the application

present in ArrayOfNumbers

Using LINQ

number elements present

Run the application

output

Example 5

In this example we will see how to get the average of the ArrayOfNumbers.

Without LINQ

get the average

Run the application

cmd

With LINQ

To get the average in LINQ, we can use the Average aggregate function.

get the average in LINQ

Note: The return type of this function is double.

Run the application

return type of this function

Example 6

In this demo we will see how to use the Aggregate function.

In my console application, I have this array of Names.
  1. 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 LINQ

achieve it

Run the application

displayed

We 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.

remove comma

Run the application

LastIndexOf method

With LINQ

string

Run the application

last string

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.

Up Next
    Ebook Download
    View all
    Learn
    View all