finding closest value in an array

前端 未结 6 1904
情歌与酒
情歌与酒 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:12

    Both Jon and Rich gave great answers with MinBy and ClosestTo. But I would never recommend using OrderBy if your intent is to find a single element. It's far too inefficient for those kinds of tasks. It's simply the wrong tool for the job.

    Here's a technique that performs marginally better than MinBy, is already included in the .NET framework, but less elegant than MinBy: Aggregate

    var nearest = array.Aggregate((current, next) => Math.Abs((long)current - targetNumber) < Math.Abs((long)next - targetNumber) ? current : next);
    

    As I said, not as elegant as Jon's method, but viable.

    Performance on my computer:

    1. For(each) Loops = fastest
    2. Aggregate = 2.5x slower than loops
    3. MinBy = 3.5x slower than loops
    4. OrderBy = 12x slower than loops

提交回复
热议问题