Aggregation in LINQ


Advertisements

Performs any type of desired aggregation and allows creating custom aggregations in LINQ.

Operator Description C# Query Expression Syntax VB Query Expression Syntax
Aggregate Operates on the values of a collection to perform custom aggregation operation Not Applicable Not Applicable
Average Average value of a collection of values is calculated Not Applicable Aggregate … In … Into Average()
Count Counts the elements satisfying a predicate function within collection Not Applicable Aggregate … In … Into Count()
LonCount Counts the elements satisfying a predicate function within a huge collection Not Applicable Aggregate … In … Into LongCount()
Max Find out the maximum value within a collection Not Applicable Aggregate … In … Into Max()
Min Find out the minimum value existing within a collection Not Applicable Aggregate … In … Into Min()
Sum Find out the sum of a values within a collection Not Applicable Aggregate … In … Into Sum()

Example

VB

Module Module1

   Sub Main()
   
      Dim num As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9}

      Dim intDivByTwo = Aggregate n In num
                       Where n > 6
                       Into Count()
      Console.WriteLine("Count of Numbers: " & intDivByTwo)

      Dim intResult = Aggregate n In num
                     Where n > 6
                     Into Average()
							
      Console.WriteLine("Average of Numbers: " & intResult)

      intResult = Aggregate n In num
                 Where n > 6
                 Into LongCount()
					  
      Console.WriteLine("Long Count of Numbers: " & intResult)

      intResult = Aggregate n In num
                 Into Max()
					  
      Console.WriteLine("Max of Numbers: " & intResult)

      intResult = Aggregate n In num
                 Into Min()
					  
      Console.WriteLine("Min of Numbers: " & intResult)

      intResult = Aggregate n In num
                 Into Sum()
					  
      Console.WriteLine("Sum of Numbers: " & intResult)

      Console.ReadLine()

   End Sub
   
End Module

When the above VB code is compiled and executed, it produces the following result −

Count of Numbers: 3
Average of Numbers: 8
Long Count of Numbers: 3
Max of Numbers: 9
Min of Numbers: 1
Sum of Numbers: 45
linq_query_operators.htm
Advertisements