Aggregate 子句 (Visual Basic)

更新:2007 年 11 月

对集合应用一个或多个聚合函数。

Aggregate element [As type] In collection _
    [, element2 [As type2] In collection2, [...]]
  [ clause ]
    Into expressionList

组成部分

  • element
    必需。用于循环访问集合的元素的变量。

  • type
    可选。element 的类型。如果不指定类型,则从 collection 推断 element 的类型。

  • collection
    必需。引用要对其进行操作的集合。

  • clause
    可选。一个或多个查询子句(例如 Where 子句),用于优化要向其应用聚合子句的查询结果。

  • expressionList
    必需。一个或多个由逗号分隔的表达式,标识要应用到集合的聚合函数。可以对聚合函数应用一个别名,以便为查询结果指定成员名称。如果不提供别名,则使用聚合函数的名称。有关示例,请参见本主题后面有关聚合函数的部分。

备注

Aggregate 子句可用于在查询中包含聚合函数。聚合函数对一组值执行检查和计算,并返回单个值。使用查询结果类型的成员可以访问计算得到的值。可以使用的标准聚合函数包括 All、Any、Average、Count、LongCount、Max、Min 和 Sum 函数。这些函数对于熟悉 SQL 中聚合的开发人员而言并不陌生。本主题的下一部分将介绍这些函数。

聚合函数的结果作为查询结果类型的字段包含在查询结果中。可以为聚合函数结果提供别名,以指定将保存聚合值的查询结果类型成员的名称。如果不提供别名,则使用聚合函数的名称。

Aggregate 子句可以开始查询,也可以作为附加子句包含在查询中。如果 Aggregate 子句开始查询,则结果是单个值,该值是 Into 子句中指定的聚合函数的结果。如果在 Into 子句中指定多个聚合函数,则查询会返回单个类型,而且,对于 Into 子句中的每个聚合函数,该类型都具有一个单独的属性,以引用该聚合函数的结果。如果 Aggregate 子句作为附加子句包含在查询中,则对于 Into 子句中的每个聚合函数,查询集合中返回的类型都具有一个单独的属性,以引用该聚合函数的结果。

聚合函数

下面的列表描述了可以在 Aggregate 子句中使用的标准聚合函数。

  • All
    如果集合中的所有元素均满足指定条件,则返回 true;否则返回 false。下面是一个示例:

    Dim customerList1 = Aggregate order In orders _
                        Into AllOrdersOver100 = All(order.Total >= 100)
    
  • Any
    如果集合中的任一元素满足指定条件,则返回 true;否则返回 false。下面是一个示例:

    Dim customerList2 = From cust In customers _
                        Aggregate order In cust.Orders _
                        Into AnyOrderOver500 = Any(order.Total >= 500)
    
  • Average
    计算集合中所有元素的平均值,或者对集合中的所有元素计算提供的表达式。下面是一个示例:

    Dim customerOrderAverage = Aggregate order In orders _
                               Into Average(order.Total)
    
  • Count
    统计集合中的元素数量。可以提供一个可选的 Boolean 表达式,以便仅统计集合中满足条件的元素数量。下面是一个示例:

    Dim customerOrderAfter1996 = From cust In customers _
                                 Aggregate order In cust.Orders _
                                 Into Count(order.OrderDate > #12/31/1996#)
    
  • Group
    引用由 Group By 或 Group Join 子句进行分组的查询结果。仅当 Group 函数位于 Group By 或 Group Join 子句的 Into 子句中时,该函数才有效。有关更多信息和示例,请参见 Group By 子句 (Visual Basic)Group Join 子句 (Visual Basic)

  • LongCount
    统计集合中的元素数量。可以提供一个可选的 Boolean 表达式,以便仅统计集合中满足条件的元素数量。将结果作为 Long 类型的值返回。有关示例,请参见 Count 聚合函数。

  • Max
    计算集合中的最大值,或对集合中的所有元素计算提供的表达式。下面是一个示例:

    Dim customerMaxOrder = Aggregate order In orders _
                           Into MaxOrder = Max(order.Total)
    
  • Min
    计算集合中的最小值,或对集合中的所有元素计算提供的表达式。下面是一个示例:

    Dim customerMinOrder = From cust In customers _
                           Aggregate order In cust.Orders _
                           Into MinOrder = Min(order.Total)
    
  • Sum
    计算集合中所有元素之和,或对集合中的所有元素计算提供的表达式。下面是一个示例:

    Dim customerTotals = From cust In customers _
                         Aggregate order In cust.Orders _
                         Into Sum(order.Total)
    

示例

下面的代码示例演示如何使用 Aggregate 子句对查询结果应用聚合函数。

Public Sub AggregateSample()
  Dim customers = GetCustomerList()

  Dim customerOrderTotal = _
      From cust In customers _
      Aggregate order In cust.Orders _
      Into Sum(order.Total), MaxOrder = Max(order.Total), _
      MinOrder = Min(order.Total), Avg = Average(order.Total)

  For Each customer In customerOrderTotal
    Console.WriteLine(customer.cust.CompanyName & vbCrLf & _
                     vbTab & "Sum = " & customer.Sum & vbCrLf & _
                     vbTab & "Min = " & customer.MinOrder & vbCrLf & _
                     vbTab & "Max = " & customer.MaxOrder & vbCrLf & _
                     vbTab & "Avg = " & customer.Avg.ToString("#.##"))
  Next
End Sub

创建用户定义的聚合函数

可以通过将扩展方法添加到 IEnumerable<T> 类型,在查询表达式中包含您自己的自定义聚合函数。然后,您的自定义方法可以对引用您的聚合函数的可枚举集合执行计算或操作。有关扩展方法的更多信息,请参见扩展方法 (Visual Basic)

例如,下面的代码示例演示了一个自定义聚合函数,该函数计算一个数字集合的中值。Median 扩展方法具有两个重载版本。第一个重载接受 IEnumerable(Of Double) 类型集合作为输入。如果对 Double 类型的查询字段调用 Median 聚合函数,则将调用此方法。可以向 Median 方法的第二个重载传递任何泛型类型。Median 方法的泛型重载接受另一个参数,该参数引用了 Func(Of T, Double) lambda 表达式,以便将集合中的类型的值投射为 Double 类型的相应值。然后,它将中值的计算委托给 Median 方法的另一个重载。有关 lambda 表达式的更多信息,请参见 lambda 表达式

Imports System.Runtime.CompilerServices

Module UserDefinedAggregates

  ' Calculate the median value for a collection of type Double.
  <Extension()> _
  Function Median(ByVal medianAggregate As IEnumerable(Of Double)) As Double
    If medianAggregate.Count = 0 Then
      Throw New InvalidOperationException("Cannot compute median for an empty set.")
    End If

    Dim sortedList = From number In medianAggregate Order By number

    Dim medianValue As Double

    Dim itemIndex = CInt(Int(sortedList.Count / 2))

    If sortedList.Count Mod 2 = 0 Then    
      ' Even number of items in list.
      medianValue = ((sortedList(itemIndex) + sortedList(itemIndex - 1)) / 2)
    Else                                  
     ' Odd number of items in list.
      medianValue = sortedList(itemIndex)
    End If

    Return medianValue
  End Function

  ' "Cast" the collection of generic items as type Double and call the 
  ' Median() method to calculate the median value.
  <Extension()> _
  Function Median(Of T)(ByVal medianAggregate As IEnumerable(Of T), _
                        ByVal selector As Func(Of T, Double)) As Double
    Return (From element In medianAggregate Select selector(element)).Median()
  End Function

End Module

下面的代码示例演示了示例查询,这些查询对 Integer 类型集合和 Double 类型集合调用 Median 聚合函数。对 Double 类型集合调用 Median 聚合函数的查询调用 Median 方法的接受 Double 类型集合作为输入的重载。对 Integer 类型集合调用 Median 聚合函数的查询调用 Median 方法的泛型重载。

Module Module1

  Sub Main()
    Dim numbers1 As Integer() = New Integer() {1, 2, 3, 4, 5}

    Dim query1 = Aggregate num In numbers1 Into Median(num)

    Console.WriteLine("Median = " & query1)

    Dim numbers2 As Double() = New Double() {1.9, 2, 8, 4, 5.7, 6, 7.2, 0}

    Dim query2 = Aggregate num In numbers2 Into Median()

    Console.WriteLine("Median = " & query2)
  End Sub

End Module

请参见

概念

Visual Basic 中的 LINQ 简介

参考

Select 子句 (Visual Basic)

From 子句 (Visual Basic)

Where 子句 (Visual Basic)

Group By 子句 (Visual Basic)

其他资源

查询 (Visual Basic)