C# linq 列表查找最接近的数字

C# linq list find closest numbers

我有一个号码列表,我想找到最接近搜索号码的四个号码。

例如,如果搜索号码是 400000 并且列表是:{150000, 250000, 400000, 550000, 850000, 300000, 200000),那么最接近的 4 个号码将是:

{300000, 400000, 250000, 550000}

如有任何帮助或建议,我们将不胜感激。

您可以使用OrderBy to order the list by the absolute value of the difference between each item and your search term, so that the first item in the ordered list is closest to your number, and the last item is furthest from the number. Then you can use the Take扩展方法来获取您需要的项目数:

var list = new List<long> {150000, 250000, 400000, 550000, 850000, 300000, 200000};
var search = 400000;
var result = list.OrderBy(x => Math.Abs(x - search)).Take(4);
Console.WriteLine(string.Join(", ", result));

输出:{400000, 300000, 250000, 550000}