Linq-aggregation

提供:Dev Guides
移動先:案内検索

LINQの集約

任意のタイプの必要な集計を実行し、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()

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

上記のVBコードがコンパイルおよび実行されると、次の結果が生成されます-

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