次の方法で共有


集計操作 (Visual Basic)

集計操作は、値のコレクションから 1 つの値を計算します。 集計操作の例として、1 か月分の 1 日の温度値から 1 日の平均温度が計算されます。

次の図は、一連の数値に対する 2 つの異なる集計操作の結果を示しています。 最初の操作では、数値が合計されます。 2 番目の操作は、シーケンス内の最大値を返します。

LINQ 集計操作を示す図。

集計操作を実行する標準のクエリ演算子メソッドを次のセクションに示します。

メソッド

メソッド名 説明 Visual Basic のクエリ式の構文 詳細情報
集計 コレクションの値に対してカスタム集計操作を実行します。 適用されません。 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
合計 コレクション内の値の合計を計算します。 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

次のコード例では、 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

合計

次のコード例では、 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

こちらも参照ください