c# - 查找数组中最小的最接近值
问题描述
我有如下代码
var searchValues = new double[] { 21.1, 21.65, 22.2, 22.75, 23.3, 23.85, 24.4, 24.95, 25.5, 26.05, 26.6, 27.15, 27.7, 28.25, 28.8, 29.35, 29.9, 30.45, 31, 31.55, 32.1, 32.65, 33.2, 33.75, 34.3, 34.85, 35.4, 35.95 };
var searchValue = 22;
double nearest = searchValues .Select(p => new { Value = p, Difference = Math.Abs(p - searchValue ) })
.OrderBy(p => p.Difference)
.First().Value;
此代码返回我 22.2 。但是我希望结果是接近 22 的最小值,即 21.65。我如何实现这一目标?我对 C# 比较陌生,希望能得到一些帮助。
解决方案
根据您的预期输出,您试图找到小于 searchValue
. 试试下面
var searchValues = new double[] { 21.1, 21.65, 22.2, 22.75, 23.3, 23.85, 24.4, 24.95, 25.5, 26.05, 26.6, 27.15, 27.7, 28.25, 28.8, 29.35, 29.9, 30.45, 31, 31.55, 32.1, 32.65, 33.2, 33.75, 34.3, 34.85, 35.4, 35.95 };
var searchValue = 22;
double nearest = searchValues
.Where(x => x <= searchValue) //Filter all values which are less than or equal to searchValue
.OrderBy(y=> y) //Order resultant values by ascending order
.LastOrDefault(); //Get the max value from an array.
Console.WriteLine(nearest == 0 && searchValue > 0 ? "Invalid Input" : $"Nearest Value : {nearest}");
推荐阅读
- java - 如何从 Java 中的内部方法类访问变量?
- python - 如何使用 selenium 和 python 从 Highcharts 图表中抓取数据?
- angular - 如何将输入传递给 Angular 组件的 SCSS?
- javascript - 尝试使用 HTML & CSS & JS 制作灯泡
- android - 在 4.12.0 版本上滑动错误 .bitmapTransform
- python - 如何使用此代码通过使用 after 命令多次直接更改我的图像
- html - Css 网格,对齐内容:结束,在我的代码中不起作用
- qt - QTimer:定时器回调可以重叠执行吗?
- netflix-zuul - 如果请求正文小于 Content-Length 标头中指定的大小并使用 tomcat APR 连接器,则可能会发生这种情况
- javascript - Bean 名称“广告”的 BindingResult 和普通目标对象都不能用作请求属性