如何获取最近数字的列表索引?
如何获取可以找到最接近数字的列表索引?
List<int> list = new List<int> { 2, 5, 7, 10 };
int number = 9;
int closest = list.Aggregate((x,y) =>
Math.Abs(x-number) < Math.Abs(y-number) ? x : y);
How to get the list index where you can find the closest number?
List<int> list = new List<int> { 2, 5, 7, 10 };
int number = 9;
int closest = list.Aggregate((x,y) =>
Math.Abs(x-number) < Math.Abs(y-number) ? x : y);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果你想要最接近的数字的索引,这可以解决问题:
If you want the index of the closest number this will do the trick:
您可以将每个项目的索引包含在匿名类中并将其传递给聚合函数,并在查询结束时可用:
You can include the index of each item in an anonymous class and pass it through to the aggregate function, and be available at the end of the query:
只需枚举索引并选择具有最小增量的索引,就像执行常规循环一样。
Just enumerate over indices and select the index with the smallest delta as you would if you did a regular loop.
对您已有的内容进行非常小的更改,因为您似乎已经有了答案:
Very minor changes to what you already have, since you seem to have the answer already:
最接近的数字是差异最小的数字:
The closest number is the one where the difference is the smallest: