find the standard deviation of all keys in a map in csharp

To find the standard deviation of all keys in a map, you can use LINQ to first get an array of all the keys, then use the StandardDeviation method from the System.Linq namespace. Here's an example:

main.cs
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        // create a map
        Dictionary<int, string> map = new Dictionary<int, string>();
        map.Add(1, "one");
        map.Add(2, "two");
        map.Add(3, "three");
        map.Add(4, "four");
        map.Add(5, "five");

        // get an array of all the keys
        int[] keys = map.Keys.ToArray();

        // calculate the standard deviation
        double stdDev = keys.StandardDeviation();

        Console.WriteLine("Standard deviation of keys: {0}", stdDev);
    }
}

// extension method to calculate standard deviation of a sequence
public static class EnumerableExtensions
{
    public static double StandardDeviation(this IEnumerable<int> values)
    {
        double average = values.Average();
        double sumOfSquares = values.Sum(val => Math.Pow(val - average, 2));
        double result = Math.Sqrt(sumOfSquares / values.Count());
        return result;
    }
}
1007 chars
38 lines

In this example, the keys array is calculated using map.Keys.ToArray(). The StandardDeviation method is then called on the keys array using the extension method defined at the bottom of the code snippet. The resulting standard deviation is printed to the console.

gistlibby LogSnag