Hello I'm trying to find closest values(which needs to be 2) from dictionary, by specified value, but seems I'm not able to find working solution.
Tried to use for first time tryied to find values using static range, but realised if value diffrence is higher than specified range my code will return wrong values so I forced to return to "drawing board"
Dictionary<double,double> valueDictionary = new Dictionary<double, double>();
valueDictionary.Add(0,10);
valueDictionary.Add(1, 25);
valueDictionary.Add(2, 35);
valueDictionary.Add(3, 55);
valueDictionary.Add(4, 100);
double valueToFind = 40;
var result = valueDictionary.Values.Where(t => t >= valueToFind - 10 && t <= valueToFind + 10).ToDictionary(t=> t,v=>v);
Debug.WriteLine("Result "+result.Count);
If we searching for value 40, then it has to return 35 and 55
valueDictionary.Add(2, 35);
valueDictionary.Add(3, 55);
If we searching for value 60, then it has to return 55 and 100
valueDictionary.Add(3, 55);
valueDictionary.Add(4, 100);
But if we searching for value 55, then its has to return it index id which are 3
Thanks for help.
Not a best solution but it does its job, just wondering is this would be possible to use linq on this solution
double valueToFind = 40;
MyObject minimum = new MyObject(){Y= 0,X = 0};// define minimum range
MyObject maximum = new MyObject(){Y = 100, X = 100}; //define maximum range
foreach (var child in tempList)//your collection
{
if (child.X <= valueToFind)// try to find lower values from our valueToFind variable
{
if (child.Y >= minimum.X)//if value is higher than our lower value, it means its close to our searching minimum value
{
minimum.Y = child.Y;
minimum.X = child.X;
}
}
else if (child.X >= valueToFind) // try to find higher values from our valueToFind variable
{
if (child.X <= maximum.X) //if value is lower than our higher value, it means its close to our searching maximum value
{
maximum.Y = child.Y;
maximum.X = child.X;
}
}
}
Debug.WriteLine("Found variables");
Debug.WriteLine(minimum.X + " " + minimum.Y);
Debug.WriteLine(maximum.X + " " + maximum.Y);
public class MyObject
{
public double X { get; set; }
public double Y { get; set; }
}