I seem to understand what you mean.
I think you are not trying to find the number that is closest to 420 among all the numbers, but to find the first group containing 420.
For 420, it is 350 and 600. For other numbers such as 610, it is 600 and 800.
Then find the closest number from these two numbers, if there is no such set of numbers that meet the requirements, then look for the true closest number.
If my guess is correct, please try the following code:
public static double SearchArray(double inValToSearch_, List<double> inArr_)
{
if (inArr_ == null || inArr_.Count == 0)
return 0;
for (int i = 0; i < inArr_.Count-1; i++)
{
if (inArr_[i] < inValToSearch_ && inArr_[i+1] > inValToSearch_)
{
return inValToSearch_ - inArr_[i] < inArr_[i + 1] - inValToSearch_ ? inArr_[i] : inArr_[i+1];
}
}
return inArr_.OrderBy(item => Math.Abs(inValToSearch_ - item)).First();
}
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.