If you have performed much in the way of basic data analysis using LINQ (Language Integrated Query), you probably have noticed that standard deviation is not included out of the box. Why Standard Deviation is missing is a mystery as LINQ does include the other basic aggregators such as min, max, avg, sum, and count. To construct a function to perform standard deviation over a set of numbers, you need to examine the math. Figure 1 shown below is the basic standard deviation function.

Figure 1: The math behind the basic stand deviation function.
In simpler terms, standard deviation is calculated as follows:
- Calculate the average of the values.
- Subtract each value from the average.
- Take the result to the second power.
- Sum up the result of steps 1-3 over all of the values.
- Divides the sum by the number of values.
- Take the square root of the result.
Create the Standard Deviation Function
Now that you are familiar with the math, you can create a function that performs this math over a set of values of type double, as shown below.
private double CalculateStdDev(IEnumerable<double> values)
{
double ret = 0;
if (values.Count() > 0)
{
//Compute the Average
double avg = values.Average();
//Perform the Sum of (value-avg)_2_2
double sum = values.Sum(d => Math.Pow(d - avg, 2));
//Put it all together
ret = Math.Sqrt((sum) / values.Count()-1);
}
return ret;
}
Read the Rest of this Article at Developer.com