共用方式為


彙總作業

更新:2007 年 11 月

彙總 (Aggregation) 作業會根據值的集合計算出單一值。彙總作業的例子是計算一個月當中日溫度總和的平均值。

下圖顯示對某個數字序列執行兩種不同彙總作業的結果。第一個作業會加總數字。第二個作業則會傳回序列中的最大值。

LINQ 彙總作業

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

方法

方法名稱

說明

C# 查詢運算式語法

Visual Basic 查詢運算式語法

詳細資訊

Aggregate

對集合中的值執行自訂彙總作業。

不適用。

不適用。

Enumerable.Aggregate

Queryable.Aggregate

Average

對集合中的值計算平均值。

不適用。

Aggregate … In … Into Average()

Enumerable.Average

Queryable.Average

Count

計算集合中的項目個數,可以選擇性地僅計算滿足述詞 (Predicate) 函式的項目個數。

不適用。

Aggregate … In … Into Count()

Enumerable.Count

Queryable.Count

LongCount

計算大型集合中的項目個數,可能選擇性地僅計算滿足述詞函式的項目。

不適用。

Aggregate … In … Into LongCount()

Enumerable.LongCount

Queryable.LongCount

Max

判斷集合中的最大值。

不適用。

Aggregate … In … Into Max()

Enumerable.Max

Queryable.Max

Min

判斷集合中的最小值。

不適用。

Aggregate … In … Into Min()

Enumerable.Min

Queryable.Min

Sum

計算集合中所有值的總和。

不適用。

Aggregate … In … Into Sum()

Enumerable.Sum

Queryable.Sum

查詢運算式語法範例

Average

下列程式碼範例會在 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

Count

下列程式碼範例會在 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

下列程式碼範例會在 Visual Basic 中使用 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

Max

下列程式碼範例會在 Visual Basic 中使用 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

下列程式碼範例會在 Visual Basic 中使用 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

下列程式碼範例會在 Visual Basic 中使用 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

進一步了解如何執行彙總作業

請參閱

概念

標準查詢運算子概觀

參考

Aggregate 子句 (Visual Basic)

System.Linq