Calculate variance with VB.NET lambda expression
I am trying to convert the following code for the variance calculation
public static double Variance(this IEnumerable<double> source)
{
double avg = source.Average();
double d = source.Aggregate(0.0,
开发者_JS百科 (total, next) => total += Math.Pow(next - avg, 2));
return d / (source.Count() - 1);
}
described on CodeProject into corresponded VB.NET lambda expression syntax, but I am stuck in the conversion of Aggregate function.
How can I implement that code in VB.NET?
The following will only work in VB 10. Prior versions didn’t support multi-line lambdas.
Dim d = source.Aggregate(0.0,
Function(total, next)
total += (next - avg) ^ 2
Return total
End Function)
Function(foo) bar
corresponds to the single-statement lambda (foo) => bar
in C# but you need the multi-line lambda here which only exists since VB 10.
However, I’m wary of the original code. Modifying total
seems like an error, since no Aggregate
overload passes its arguments by reference. So I’m suggesting that the original code is wrong (even though it may actually compile), and that the correct solution (in VB) would look like this:
Dim d = source.Aggregate(0.0, _
Function(total, next) total + (next - avg) ^ 2)
Furthermore, this doesn’t require any multi-line lambdas, and thus also works on older versions of VB.
精彩评论