我编写了以下通用LINQ扩展来计算Visual Basic 2010中的加权平均值:
<Extension()>
Function WeightedAverage(Of T)(ByVal source As IEnumerable(Of T),
ByVal selectorValue As Func(Of T, Integer),
ByVal selectorWeight As Func(Of T, Integer)) As Double
Dim weightedValueSum As Double
Dim weightSum As Integer
weightedValueSum = (From element In source
Select (selectorValue(element) * selectorWeight(element))).Sum()
weightSum = (From element In source
Select selectorWeight(element)).Sum()
If weightSum <> 0 Then
Return weightedValueSum / weightSum
Else
Return 0
End If
End Function
如何将此函数作为另一个LINQ查询的聚合函数调用?
我按照以下方式尝试了它:
Dim q1 = From jd In oContext.JobDatas
Where jd.Year = 2011
Select jd
Dim q2 = Aggregate num In q1 Into WeightedAverage(num.AvSalary, num.NumPosHolder)
Visual Basic 2010编辑器告诉我以下代码的第二个查询(q2)不是有效语句。在第一个第二个参数之间的逗号,它说:“)”必需。怎么了?
答案 0 :(得分:1)
使用聚合函数有什么特别的理由吗?如果您只想计算第一个查询的加权平均值,则可以执行以下操作:
Dim q1 = From jd In oContext.JobDatas
Where jd.Year = 2011
Select jd
Dim avg As Double = q1.WeighedAverage(Function(num) num.AvSalary, Function(num) num.NumPosHolder)