LINQ查找大于/小于输入的最接近的数字 [英] LINQ to find the closest number that is greater / less than an input

查看:385
本文介绍了LINQ查找大于/小于输入的最接近的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有此号码列表:

List<int> = new List<int>(){3,5,8,11,12,13,14,21}

假设我要获取小于11的最接近的数字,那就是8 假设我想获得大于13的最接近数字,即14.

Suppose that I want to get the closest number that is less than 11, it would be 8 Suppose that I want to get the closest number that is greater than 13 that would be 14.

列表中的数字不能重复并且总是有序的.我该如何为此编写Linq?

The numbers in list can't be duplicated and are always ordered. How can I write Linq for this?

推荐答案

使用Linq假定列表是有序的,我会这样做:

with Linq assuming that the list is ordered I would do it like this:

var l = new List<int>() { 3, 5, 8, 11, 12, 13, 14, 21 };
var lessThan11 = l.TakeWhile(p => p < 11).Last();
var greaterThan13 = l.SkipWhile(p => p <= 13).First();

由于我收到了有关此答案的负面反馈,为了让人们看到该答案,并且尽管被接受,请不要再做进一步介绍了,我探究了有关BinarySearch的其他评论,并决定在此处添加第二个选项(进行一些细微的更改).

As I have received negative feedback about this answer and for the sake of people that may see this answer and while it's accepted don't go further, I explored the other comments regarding BinarySearch and decided to add the second option in here (with some minor change).

这不是在其他地方提供的足够方法:

This is the not sufficient way presented somewhere else:

var l = new List<int>() { 3, 5, 8, 11, 12, 13, 14, 21 };
var indexLessThan11 = ~l.BinarySearch(10) -1;
var value = l[indexLessThan11];

现在,上面的代码无法解决值10实际上可能在列表中的情况(在这种情况下,不应反转索引)!所以好的方法是做到这一点:

Now the code above doesn't cope with the fact that the value 10 might actually be in the list (in which case one shouldn't invert the index)! so the good way is to do it:

var l = new List<int>() { 3, 5, 8, 11, 12, 13, 14, 21 };
var indexLessThan11 = l.BinarySearch(10);
if (indexLessThan11 < 0) // the value 10 wasn't found
{    
    indexLessThan11 = ~indexLessThan11;
    indexLessThan11 -= 1;
}
var value = l[indexLessThan11];

我只想指出:

l.BinarySearch(11) == 3
//and
l.BinarySearch(10) == -4;

这篇关于LINQ查找大于/小于输入的最接近的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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