聚合操作(Visual Basic)

聚合操作从值集合计算一个值。 聚合运算的一个示例是基于一个月的每日温度值来计算日平均温度。

下图显示了对数字序列的两个不同的聚合操作结果。 第一个运算对数字求和。 第二个操作返回序列中的最大值。

显示 LINQ 聚合操作的插图。

以下部分列出了执行聚合操作的标准查询运算符方法。

方法

方法名 DESCRIPTION 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

查询表达式语法示例

平均值

下面的代码示例使用 Aggregate Into Average Visual Basic 中的子句计算表示温度的数字数组中的平均温度。


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

另请参阅