Aggregate 子句 (Visual Basic)

將一或多個彙總函式套用至集合。

語法

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, AnyAverageCountLongCountMaxMinSum 函式。 對於熟悉 SQL 中彙總的開發人員而言,這些函式很熟悉。 本主題的下一節將說明它們。

彙總函式的結果會包含在查詢結果中,作為查詢結果類型的欄位。 您可以針對彙總函式結果提供別名,以指定將保存彙總值的查詢結果類型成員名稱。 如果未提供別名,則會使用彙總函式的名稱。

Aggregate 子句可以開始查詢,也可以包含在查詢中作為其他子句。 如果 Aggregate 子句開始查詢,則結果為單一值,這是 Into 子句中指定之彙總函式的結果。 如果在 Into 子句中指定多個彙總函式,查詢會傳回具有個別屬性的單一型別,以參考 Into 子句中每個彙總函式的結果。 如果 Aggregate 子句包含在查詢中作為其他子句,則查詢集合中傳回的型別會有不同的屬性,以參考 Into 子句中每個彙總函式的結果。

彙總函式

以下是可與 Aggregate 子句搭配使用的標準彙總函式。

全部

如果集合中的所有元素都滿足指定的條件,則傳回 true,否則傳回 false。 以下是一個範例:

Dim customerList1 = Aggregate order In orders
                    Into AllOrdersOver100 = All(order.Total >= 100)

任意

如果集合中的任何元素都滿足指定的條件,則傳回 true,否則傳回 false。 以下是一個範例:

Dim customerList2 = From cust In customers
                    Aggregate order In cust.Orders
                    Into AnyOrderOver500 = Any(order.Total >= 500)

平均

計算集合中所有元素的平均值,或計算集合中所有元素的提供運算式。 以下是一個範例:

Dim customerOrderAverage = Aggregate order In orders
                           Into Average(order.Total)

計數

計算集合中的元素數。 您可以提供選擇性的 Boolean 運算式,只計算集合中滿足條件的元素數目。 以下是一個範例:

Dim customerOrderAfter1996 = From cust In customers
                             Aggregate order In cust.Orders
                             Into Count(order.OrderDate > #12/31/1996#)

群組

參考群組為 Group ByGroup Join 子句結果的查詢結果。 Group 函式只在 Group ByGroup Join 子句的 Into 子句中有效。 如需詳細資訊和範例,請參閱 Group By 子句Group Join 子句

LongCount

計算集合中的元素數。 您可以提供選擇性的 Boolean 運算式,只計算集合中滿足條件的元素數目。 以 Long 傳回結果。 如需範例,請參閱 Count 彙總函式。

最大值

計算集合中的最大值,或計算集合中所有元素的提供運算式。 以下是一個範例:

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> 型別,以在查詢運算式中包含自己的自訂彙總函式。 然後,您的自訂方法可以在參考彙總函式的可列舉集合上執行計算或運算。 如需擴充方法的詳細資訊,請參閱擴充方法

例如,下列範例顯示自訂彙總函式,可計算數字集合的中位數。 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 values As IEnumerable(Of Double)) As Double
        If values.Count = 0 Then
            Throw New InvalidOperationException("Cannot compute median for an empty set.")
        End If

        Dim sortedList = From number In values
                         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 values As IEnumerable(Of T),
                          ByVal selector As Func(Of T, Double)) As Double
        Return (From element In values Select selector(element)).Median()
    End Function

End Module

下列範例示範在型別 Integer 的集合上,以及型別 Double 的集合上呼叫 Median 彙總函式的範例查詢。 在型別 Double 的集合上呼叫 Median 彙總函式的查詢會呼叫 Median 方法的多載,以接受型別 Double 的集合作為輸入。 在型別 Integer 的集合上呼叫 Median 彙總函式的查詢會呼叫 Median 方法的泛型多載。

Module Module1

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

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

        Console.WriteLine("Median = " & query1)

        Dim numbers2 = {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

另請參閱