find the variance of all values in a map in csharp

To find the variance of all values in a map in C#, you can use LINQ to calculate the sample variance of the collection of values.

Assuming you have a Dictionary<TKey, TValue> called myMap where TValue is numeric, you can use the following code:

main.cs
var values = myMap.Values;
if (values.Count < 2)
{
    throw new InvalidOperationException("Map must have at least 2 values to calculate variance");
}

double mean = values.Average();
double variance = values.Sum(v => Math.Pow(v - mean, 2)) / (values.Count - 1);
263 chars
9 lines

This code calculates the mean of all the values in the map using the Average LINQ method, and then calculates the sum of the squares of the differences between each value and the mean using the Sum and Math.Pow methods. Finally, it divides the sum by n-1 to get the sample variance.

Note that since variance is a statistical concept, you may also want to add the System.Linq and System namespaces at the top of your file.

gistlibby LogSnag