共用方式為


匯總作業 (Visual Basic)

匯總作業會從值的集合計算單一值。 匯總運算的範例是從一整個月的每日溫度值中計算平均每日溫度。

下圖顯示數位序列上兩個不同匯總作業的結果。 第一個作業會加總數位。 第二個作業會傳回序列中的最大值。

顯示 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

計數

下列程式代碼範例使用 Aggregate Into Count Visual Basic 中的 子句來計算陣列中大於或等於 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

另請參閱