在字典中查找最接近给定值的值 C#
Find closest value to a given value in a dictionary c#
我有一本字典,我想找出最接近给定值的“关键”值,下面是我的字典。
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;
所以我想找出哪个键最接近1。我需要键值对returned,所以它应该return [2.4, 5000]。
嗯,您可能会问自己字典是否是解决这些类型问题的正确结构,但假设这是给定的(以解决其他问题),您可以执行以下操作:
var bestMatch = dictionary.OrderBy(e => Math.Abs(e.Key - givenValue)).FirstOrDefault();
如果您需要执行许多此类查询,这将是非常低效的。
下面的效率高一点:
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);
}
我有一本字典,我想找出最接近给定值的“关键”值,下面是我的字典。
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;
所以我想找出哪个键最接近1。我需要键值对returned,所以它应该return [2.4, 5000]。
嗯,您可能会问自己字典是否是解决这些类型问题的正确结构,但假设这是给定的(以解决其他问题),您可以执行以下操作:
var bestMatch = dictionary.OrderBy(e => Math.Abs(e.Key - givenValue)).FirstOrDefault();
如果您需要执行许多此类查询,这将是非常低效的。
下面的效率高一点:
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);
}