LINQ获取最接近的值? [英] LINQ to Get Closest Value?

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

问题描述

我有一个列表,拥有的MyStuff float类型的属性。

I have a List, MyStuff has a property of Type Float.

有与10,20,22,30属性值的对象。

There are objects with property values of 10,20,22,30.

我需要编写找到最接近21的对象,在这种情况下,会发现20和22的对象的查询。然后,我需要写一个找到的对象关闭到而不超过21,并且它将与20的值返回的对象。

I need to write a query that finds the objects closest to 21, in this case it would find the 20 and 22 object. Then I need to write one that finds the object closes to 21 without going over, and it would return the object with a value of 20.

我不知道在哪里/如何开始这一个。帮助?

I have no idea where/how to begin with this one. Help?

感谢。

更新 - 哇这里有这么多的真棒响应。谢谢!我不知道要遵循哪一种,所以我会尝试他们所有。有一件事,可能使这更(或更少),有趣的是,相同的查询将不得不申请到LINQ到SQL实体,所以有可能从MS的LINQ论坛收获答案将最好的工作?不知道。

Update - wow there are so many awesome responses here. Thanks! I don't know which one to follow so I will try them all. One thing that might make this more (or less) interesting is that the same query will have to apply to LINQ-to-SQL entities, so possibly the answer harvested from the MS Linq forums will work the best? Don't know.

推荐答案

下面是满足线性时间的第二个查询的解决方案:

Here's a solution that satisfies the second query in linear time:

var pivot = 21f;
var closestBelow = pivot - numbers.Where(n => n <= pivot)
                                  .Min(n => pivot - n);

(来自上面已修改为自下而上的澄清之后)

(Edited from 'above' to 'below' after clarification)

对于第一个查询,这将是最容易使用 MoreLinq MinBy 扩展:

As for the first query, it would be easiest to use MoreLinq's MinBy extension:

var closest = numbers.MinBy(n => Math.Abs(pivot - n));

它也可以做到这一点,在线性时间标准LINQ,但通过2次源:

It's also possible to do it in standard LINQ in linear time, but with 2 passes of the source:

var minDistance = numbers.Min(n => Math.Abs(pivot - n));
var closest = numbers.First(n => Math.Abs(pivot - n) == minDistance);

如果效率是不是一个问题,你可以排序的序列,并挑选在的第一个值O(N * log n)的正如其他人发布的。

If efficiency is not an issue, you could sort the sequence and pick the first value in O(n * log n) as others have posted.

这篇关于LINQ获取最接近的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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