我编写了以下通用 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) 不是有效语句。在第一个和第二个参数之间的逗号上说:“)”需要。怎么了?