Find closest value to a given value in a dictionary c#

c#, dictionary, key-value, numbers

Solution

Well, you may ask yourself if a dictionary is the right structure for solving these types of problems, but assuming that this is a given (to address other concerns), you could do the following:

var bestMatch = dictionary.OrderBy(e => Math.Abs(e.Key - givenValue)).FirstOrDefault();

This is going to be very inefficient, if you need to do many such queries though.

The following is a bit more efficient:

Tuple<double, KeyValuePair<double, int>> bestMatch = null;
foreach (var e in dictionary)
{
    var dif = Math.Abs(e.Key - givenValue);
    if (bestMatch == null || dif < bestMatch.Item1)
        bestMatch = Tuple.Create(dif, e);
}

Problem

I have a dictionary and I want to find out which of the ‘key’ values is the closest to a given value, here is my dictionary below. ``` Dictionary<double, int> dictionary = new Dictionary<double, int>(); dictionary.Add(2.4, 5000); dictionary.Add(6, 2000); dictionary.Add(12, 1000); dictionary.Add(24, 500); dictionary.Add(60, 200); dictionary.Add(120, 100); dictionary.Add(240, 50); dictionary.Add(600, 20); dictionary.Add(1200, 10); dictionary.Add(2400, 5); dictionary.Add(6000, 2); dictionary.Add(12000, 1); givenValue = 1; ``` So I want to find out which of the keys is the closest to 1. I need the key value pair to be returned, so it should return [2.4, 5000].

Original source