如何从一个List&LT最接近的数字; INT>使用LINQ? [英] How to get the closest number from a List<int> with LINQ?

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

问题描述

如何从一个列表&LT最接近的数字; INT> 使用LINQ?

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到对象和名单很长,我会用:

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);

这方法是略高于安东尼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&LT最接近的数字; INT&GT;使用LINQ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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