Peter Horak
Peter Horak

Reputation: 21

Generic LINQ extension for calculating weighted average in Visual Basic 2010

I wrote the following generic LINQ extension for calculating weighted average in 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

How can I call this function as an Aggregate function of another LINQ query?

I tried it in the following way:

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)

The Visual Basic 2010 editor is telling me that the second query (q2) of the following code is not valid statement. On the comma between the first an second argument it's saying: ")" required. What's wrong?

Upvotes: 1

Views: 1143

Answers (1)

Meta-Knight
Meta-Knight

Reputation: 17845

Is there any particular reason to use the Aggregate function? If you just want to calculate the weighed average of the first query, you could do this:

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)

Upvotes: 1

Related Questions