find the median of all values in a map in csharp

To find the median of all values in a C# map (i.e. Dictionary), we need to first extract all the values, sort them and then compute the median.

Here's a code snippet to accomplish this:

main.cs
Dictionary<string, int> map = new Dictionary<string, int>();

// Add some key-value pairs to the map
map.Add("a", 4);
map.Add("b", 2);
map.Add("c", 7);
map.Add("d", 3);

// Extract all the values from the map
List<int> values = map.Values.ToList();

// Sort the list of values
values.Sort();

// Compute the median
int median;
int mid = values.Count / 2;
if (values.Count % 2 == 0)
{
    // Even number of values, so take the average of the middle two
    median = (values[mid - 1] + values[mid]) / 2;
}
else
{
    // Odd number of values, so take the middle value
    median = values[mid];
}

Console.WriteLine("Median: " + median);
634 chars
30 lines

In this example, we have a Dictionary called map with four key-value pairs. We extract all the values into a List<int>, sort the list and compute the median using the standard formula for calculating the median. Finally, we print the median value to the console.

gistlibby LogSnag