首页 > 解决方案 > 查找数组中最小的最接近值

问题描述

我有如下代码

    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# 比较陌生,希望能得到一些帮助。

标签: c#.netlinq

解决方案


根据您的预期输出,您试图找到小于 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}");

.net 小提琴


推荐阅读