Skip to content

Instantly share code, notes, and snippets.

@alantsai
Created January 3, 2016 23:44
Show Gist options
  • Save alantsai/aeae625d0eba703c3ff6 to your computer and use it in GitHub Desktop.
Save alantsai/aeae625d0eba703c3ff6 to your computer and use it in GitHub Desktop.
public static double WeightedAverage<T>(this IEnumerable<T> records, Func<T, double> value, Func<T, double> weight)
{
double weightedValueSum = records.Sum(x => value(x) * weight(x));
double weightSum = records.Sum(x => weight(x));
if (weightSum != 0)
return weightedValueSum / weightSum;
else
throw new DivideByZeroException("Your message here");
}
@treker7
Copy link

treker7 commented Mar 20, 2025

Single pass implementation ->

public static double WeightedMean<TSource>(this IEnumerable<TSource> list,
    Func<TSource, double> valueSelector, Func<TSource, double> weightSelector) =>
    list.Aggregate(
        new { Sum = 0.0, SumWeights = 0.0 },
        (accumulator, l) =>
        {
            double sum = valueSelector(l) * weightSelector(l);
            double weight = weightSelector(l);

            return new { Sum = sum + accumulator.Sum, SumWeights = weight + accumulator.SumWeights };
        },
        accumulator => (accumulator.SumWeights != 0) ? accumulator.Sum / accumulator.SumWeights : 0
    );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment