LINQでの集約

任意のタイプの目的の集計を実行し、LINQでカスタム集計を作成できるようにします。

オペレーター 説明 C#クエリ式の構文 VBクエリ式の構文
集計 コレクションの値を操作して、カスタム集計操作を実行します 適用できません 適用できません
平均 値のコレクションの平均値が計算されます 適用できません Aggregate…In…IntoAverage()
カウント コレクション内の述語関数を満たす要素をカウントします 適用できません Aggregate…In…IntoCount()
LonCount 膨大なコレクション内の述語関数を満たす要素をカウントします 適用できません Aggregate…In…IntoLongCount()
マックス コレクション内の最大値を見つける 適用できません 集約…In…IntoMax()
最小 コレクション内に存在する最小値を見つける 適用できません 集約…In…IntoMin()
和 コレクション内の値の合計を調べる 適用できません Aggregate…In…IntoSum()

例

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