函数返回最接近数组元素的整数

Ash*_*aei 3 c# arrays function

我想制作一个函数,它给出一个数组,返回与数字最近的元素。

下面是一些例子:

int[] arr = new int[] {12, 48, 50, 100};
my_function(1, arr); // returns 12.
my_function(40, arr); // returns 48.
my_function(49, arr); // returns 50; in two element with equal distance, returns greater number
my_function(70, arr); // returns 50.
my_function(10005, arr); // returns 100.
Run Code Online (Sandbox Code Playgroud)

抱歉,我不知道如何编写此函数。

Far*_*ani 6

private int GetNearest(int[] array,int number)
{
    return array.OrderBy(x => Math.Abs((long)x - number)).FirstOrDefault();
}
Run Code Online (Sandbox Code Playgroud)

如果要确保在绝对差相同的情况下较大的数字在较小的数字之前,请在.ThenByDescending(a => a)后面添加OrderBy(x => Math.Abs((long)x - number))

private int GetNearest(int[] array,int number)
{
    return array.OrderBy(x => Math.Abs((long)x - number)).ThenByDescending(a => a).FirstOrDefault();
}
Run Code Online (Sandbox Code Playgroud)

  • 嗯,这没有给出 _my_function(49, arr) 的预期结果;预期为 50,但它返回 48 (3认同)