LINQ聚合


聚合

執行任何型別的所需的聚合,並允許在建立自定義LINQ聚合。

操作 描述 C#查詢表示式語法 VB查詢表示式語法
Aggregate 對集合的值進行操作執行自定義聚合操作 不適用 不適用
Average 計算集合的平均值 不適用 Aggregate … In … Into Average()
Count 計算在收集謂詞功能的元素 不適用 Aggregate … In … Into Count()
LonCount 計算一個巨大的集合中滿足謂詞函式的元素 不適用 Aggregate … In … Into LongCount()
Max 找出一個集合中的最大值 不適用 Aggregate … In … Into Max()
Min 找出一個集合中的最小值 不適用 Aggregate … In … Into Min()
Sum 計算一個集合中的值的總和 不適用 Aggregate … In … Into Sum()

範例

VB

Module Module1
  Sub Main()
     Dim num As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9}

     Dim intDivByTwo = Aggregate n In num
                       Where n > 6
                       Into Count()
        Console.WriteLine("Count of Numbers: " & intDivByTwo)

     Dim intResult = Aggregate n In num
                     Where n > 6
                     Into Average()
        Console.WriteLine("Average of Numbers: " & intResult)

     intResult = Aggregate n In num
                 Where n > 6
                 Into LongCount()
        Console.WriteLine("Long Count of Numbers: " & intResult)

     intResult = Aggregate n In num
                 Into Max()
        Console.WriteLine("Max of Numbers: " & intResult)

     intResult = Aggregate n In num
                 Into Min()
        Console.WriteLine("Min of Numbers: " & intResult)

     intResult = Aggregate n In num
                 Into Sum()
        Console.WriteLine("Sum of Numbers: " & intResult)

        Console.ReadLine()

    End Sub
End Module

當上述的VB程式碼被編譯和執行時,它產生了以下結果:

Count of Numbers: 3
Average of Numbers: 8
Long Count of Numbers: 3
Max of Numbers: 9
Min of Numbers: 1
Sum of Numbers: 45