How do I find the closest array element to an arbitrary (non-member) number?

前端 未结 5 1463
闹比i
闹比i 2021-01-18 13:48

Seemingly similar questions: \"Finding closest number in an array\" (in Java) and \"find nearest match to array of doubles\" (actually a geography problem).

5条回答
  •  情歌与酒
    2021-01-18 14:41

    One way to do this using LINQ is like this:

    public int GetClosestIndex( List doublelist, double targetvalue )
    {
      return doublelist.IndexOf(doublelist.OrderBy(d => Math.Abs(d - targetvalue)).ElementAt(0));
    }
    

    It might have some performance issues, but If the list is not that long, it should not pose a problem. Also, if two elements are equally distant from the target value, it will return the first index of those.

提交回复
热议问题