集計操作 (Visual Basic)

集計の操作では、値の集合体から単一の値が計算されます。 たとえば、1 か月分の毎日の気温値から 1 日あたりの平均の気温値を計算することが集計操作です。

次の図は、数値のシーケンスに対する 2 つの集計処理の結果を示しています。 最初の処理で数値が合計されます。 2 つ目の処理でシーケンスの最大値が返されます。

Illustration that shows LINQ aggregation operations.

次のセクションでは、集計処理を実行する標準クエリ演算子メソッドの一覧を示します。

メソッド

メソッド名 説明 Visual Basic のクエリ式の構文 説明
Aggregate コレクションの値に対してカスタム集計処理を実行します。 該当なし。 Enumerable.Aggregate

Queryable.Aggregate
平均 値のコレクションの平均値を計算します。 Aggregate … In … Into Average() Enumerable.Average

Queryable.Average
カウント コレクションの要素数をカウントします。述語関数を満たす要素のみをカウントすることもできます。 Aggregate … In … Into Count() Enumerable.Count

Queryable.Count
LongCount 大規模なコレクションの要素数をカウントします。述語関数を満たす要素のみをカウントすることもできます。 Aggregate … In … Into LongCount() Enumerable.LongCount

Queryable.LongCount
Max または MaxBy コレクション内の最大値を決定します。 Aggregate … In … Into Max() Enumerable.Max
Enumerable.MaxBy
Queryable.Max
Queryable.MaxBy
Min または MinBy コレクション内の最小値を決定します。 Aggregate … In … Into Min() Enumerable.Min
Enumerable.MinBy
Queryable.Min
Queryable.MinBy
Sum コレクション内にある値の合計を計算します。 Aggregate … In … Into Sum() Enumerable.Sum

Queryable.Sum

クエリ式の構文例

平均

次のコード例では、Visual Basic の Aggregate Into Average 句を使用して、温度を表す数値配列の平均温度を計算します。


Dim temperatures() As Double = {72.0, 81.5, 69.3, 88.6, 80.0, 68.5}

Dim avg = Aggregate temp In temperatures Into Average()

' Display the result.
MsgBox(avg)

' This code produces the following output:

' 76.65

カウント

次のコード例は、Visual Basic の Aggregate Into Count 句を使用して、80 以上の値が配列に何個含まれるかをカウントします。


Dim temperatures() As Double = {72.0, 81.5, 69.3, 88.6, 80.0, 68.5}

Dim highTemps As Integer = Aggregate temp In temperatures Into Count(temp >= 80)

' Display the result.
MsgBox(highTemps)

' This code produces the following output:

' 3

LongCount

次のコード例は、Aggregate Into LongCount 句を使用して、配列に含まれる値の数をカウントします。


Dim temperatures() As Double = {72.0, 81.5, 69.3, 88.6, 80.0, 68.5}

Dim numTemps As Long = Aggregate temp In temperatures Into LongCount()

' Display the result.
MsgBox(numTemps)

' This code produces the following output:

' 6

最大

次のコード例では、Aggregate Into Max 句を使用して、温度を表す数値配列の最高温度を計算します。


Dim temperatures() As Double = {72.0, 81.5, 69.3, 88.6, 80.0, 68.5}

Dim maxTemp = Aggregate temp In temperatures Into Max()

' Display the result.
MsgBox(maxTemp)

' This code produces the following output:

' 88.6

Min

次のコード例では、Aggregate Into Min 句を使用して、温度を表す数値配列の最低温度を計算します。


Dim temperatures() As Double = {72.0, 81.5, 69.3, 88.6, 80.0, 68.5}

Dim minTemp = Aggregate temp In temperatures Into Min()

' Display the result.
MsgBox(minTemp)

' This code produces the following output:

' 68.5

SUM

次のコード例では、Aggregate Into Sum 句を使用して、経費を表す値の配列から経費の総額を計算します。


Dim expenses() As Double = {560.0, 300.0, 1080.5, 29.95, 64.75, 200.0}

Dim totalExpense = Aggregate expense In expenses Into Sum()

' Display the result.
MsgBox(totalExpense)

' This code produces the following output:

' 2235.2

関連項目