1

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

4

1 回答 1

1

使用 Aggregate 函数有什么特别的原因吗?如果您只想计算第一个查询的加权平均值,您可以这样做:

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)
于 2012-05-14T16:02:57.410 回答