int[] array = new int[5]{5,7,8,15,20};
int TargetNumber = 13;
For a target number, I want to find the closest number in an array. For example, when the target number is 13, the closest number to it in the array above is 15. How would I accomplish that programmatically in C#?
EDIT: Have adjusted the queries below to convert to using
longarithmetic, so that we avoid overflow issues.I would probably use MoreLINQ‘s
MinBymethod:Or you could just use:
… but that will sort the whole collection, which you really don’t need. It won’t make much difference for a small array, admittedly… but it just doesn’t feel quite right, compared with describing what you’re actually trying to do: find the element with the minimum value according to some function.
Note that both of these will fail if the array is empty, so you should check for that first.