finding closest value in an array

前端 未结 6 1866
情歌与酒
情歌与酒 2020-11-27 20:56
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, whe

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 21:30

    EDIT: Have adjusted the queries below to convert to using long arithmetic, so that we avoid overflow issues.

    I would probably use MoreLINQ's MinBy method:

    var nearest = array.MinBy(x => Math.Abs((long) x - targetNumber));
    

    Or you could just use:

    var nearest = array.OrderBy(x => Math.Abs((long) x - targetNumber)).First();
    

    ... 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.

提交回复
热议问题