彙總作業 (Visual Basic)

彙總運算會計算值集合中的單一值。 彙總運算的一個範例是,當您使用一個月中每天的溫度值來計算每天平均溫度時。

下圖顯示一系列數字之三個不同彙總作業的結果。 第一項作業會加總這些數字。 第二個作業會傳回序列中的最大值。

Illustration that shows LINQ aggregation operations.

下節列出執行彙總作業的標準查詢運算子方法。

方法

方法名稱 描述 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
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

另請參閱