C# 舍入到列表值

C# Round to list values

我正在尝试将结果值舍入到列表中的下一个数字。

如果值为 (187) 我需要将结果设置为 (240)

int[] list = new int[] { 16, 25, 35, 50, 70, 95, 120, 150, 185, 240, 300, 400 };
double max;
max = list.Where(x => x <= result).Max();

但这不起作用。

你很接近:

list.Where(x => x >= result).Min();

您只希望第一项大于或等于您的预期结果:

var max = list.FirstOrDefault(x => x >= result)

注意:这假设列表是有序的,正如您的示例所暗示的那样。

如果你想在没有匹配的情况下得到异常,那么只需使用 First:

var max = list.First(x => x >= result)

如果要向上舍入,可以在列表中减去你的值后,找出哪个值大于等于0。

max = list
    .OrderBy(x => x) // Can be skipped if list is ordered.
    .FirstOrDefault(x => x - value >= 0) // if "value" is 187, max will be 240.

如果 "max" 值为 null,请确保您有可以处理的东西。

希望对您有所帮助。

尝试使用 List.BinarySearch

Returns the zero-based index of item in the sorted List, if item is found; otherwise, a negative number that is the bitwise complement of the index of the next element that is larger than item or, if there is no larger element, the bitwise complement of Count.

var list = new List<int> { 16, 25, 35, 50, 70, 95, 120, 150, 185, 240, 300, 400 };

int index = list.BinarySearch(result);
int rounded;
if (index < 0)
{
    if (~index == list.Count)
    {
        throw new InvalidOperationException("Number is too big.");
    }
    rounded = list[~index];
}
else
{
    rounded = list[index];
}

该方法的渐近复杂度为O(log n),其中n是列表的长度,而Where/First的复杂度为O(n),这对你的情况可能无关紧要,但仍然很高兴知道。

如果你想要最接近的值

var list = new List<int> { 16, 25, 35, 50, 70, 95, 120, 150, 185, 240, 300, 400 };
int value = 187;
var nearestValue = (from v in list
        let  d = Math.Abs(value - v)
        orderby d
        select v)
    .FirstOrDefault();