如何从 List<int> 中获取最接近的数字用 LINQ? [英] How to get the closest number from a List&lt;int&gt; with LINQ?

查看:27
本文介绍了如何从 List<int> 中获取最接近的数字用 LINQ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 LINQ 从 List 中获取最接近的数字?

How to get the closest number from a List<int> with LINQ?

例如:

List<int> numbers = new List<int>();
numbers.Add(2);
numbers.Add(5);
numbers.Add(7);
numbers.Add(10)

我需要在列表中找到最接近数字 9 的值.在本例中为 10.

I need to find the closest value in the list to number 9. In this case 10.

如何使用 LINQ 执行此操作?

How can I do this with LINQ?

推荐答案

如果你使用 LINQ to Objects 并且列表很长,我会使用:

If you use LINQ to Objects and the list is long, I would use:

List<int> list = new List<int> { 2, 5, 7, 10 };
int number = 9;

int closest = list.Aggregate((x,y) => Math.Abs(x-number) < Math.Abs(y-number) ? x : y);

此方法比 Anthony Pegram 建议的解决方案稍微复杂一些,但它的优点是您不必先对列表进行排序.这意味着您的时间复杂度为 O(n) 而不是 O(n*log(n)),内存使用量为 O(1) 而不是 O(n).

This method is slightly more complex than the solution that Anthony Pegram suggested, but it has as advantage that you don't have to sort the list first. This means that you have a time complexity of O(n) instead of O(n*log(n)) and a memory usage of O(1) instead of O(n).

这篇关于如何从 List<int> 中获取最接近的数字用 LINQ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆