Compare value with array and get closest value to it
arrays, c#, compare
Solution
You can do this with some simple mathematics and there are different approaches.
LINQ
Double searchValue = ...;
Double nearest = w.Select(p => new { Value = p, Difference = Math.Abs(p - searchValue) })
.OrderBy(p => p.Difference)
.First().Value;
Manually
Double[] w = { 1000, 2000, 3000, 4000, 5000 };
Double searchValue = 3001;
Double currentNearest = w[0];
Double currentDifference = Math.Abs(currentNearest - searchValue);
for (int i = 1; i < w.Length; i++)
{
Double diff = Math.Abs(w[i] - searchValue);
if (diff < currentDifference)
{
currentDifference = diff;
currentNearest = w[i];
}
}
Problem
I'm a rookie in C# and I'm trying to learn that language. Can you guys give me a tip how I can compare an array with a value picking the lowest from it? like: ``` Double[] w = { 1000, 2000, 3000, 4000, 5000 }; double min = double.MaxValue; double max = double.MinValue; foreach (double value in w) { if (value < min) min = value; if (value > max) max = value; } Console.WriteLine(" min:", min); ``` gives me the lowest value of `w`, how can I compare now? If I have: ``` int p = 1001 + 2000; // 3001 ``` how can I compare now with the list of the array and find out that the (3000) value is the nearest value to my "Searchvalue"?