LINQ 中的聚合
执行任何类型的所需聚合并允许在 LINQ 中创建自定义聚合。
运算符 | 描述 | C# 查询表达式语法 | VB 查询表达式语法 |
---|---|---|---|
聚合 | 对集合的值进行操作以执行自定义聚合操作 | 不适用 | 不适用 |
平均值 | 平均值计算一组值的值 | 不适用 | 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