linqstandard-deviation

Standard Deviation in LINQ


Does LINQ model the aggregate SQL function STDDEV() (standard deviation)?

If not, what is the simplest / best-practices way to calculate it?

Example:

  SELECT test_id, AVERAGE(result) avg, STDDEV(result) std 
    FROM tests
GROUP BY test_id

Solution

  • You can make your own extension calculating it

    public static class Extensions
    {
        public static double StdDev(this IEnumerable<double> values)
        {
           double ret = 0;
           int count = values.Count();
           if (count  > 1)
           {
              //Compute the Average
              double avg = values.Average();
    
              //Perform the Sum of (value-avg)^2
              double sum = values.Sum(d => (d - avg) * (d - avg));
    
              //Put it all together
              ret = Math.Sqrt(sum / count);
           }
           return ret;
        }
    }
    

    If you have a sample of the population rather than the whole population, then you should use ret = Math.Sqrt(sum / (count - 1));.

    Transformed into extension from Adding Standard Deviation to LINQ by Chris Bennett.