0

我有一组三个double值作为 LINQ 查询中匿名表达式的一部分。它看起来像这样:

from item in collection where
     Min(val1-val2, item.Property1, somethingElse) > item.Property2
     select item;

如何获得括号中表达式的最小值?Math.Min 只接受两个参数。我应该只使用匿名 List.Min() 吗?有更好的方法吗?

4

3 回答 3

2
var items = collection
    .Where(i => new[] { val1 - val2, item.Property1, somethingElse }.Min() > i.Property2)

或者,您可以只使用Min两次 ie Min(val1 - val2, Min(item.Property1, somethingElse))。如果val1 - val2andsomethingElse是常量,那么您可以将它移到Where子句之外,这也会使事情变得更简单。

double min = Min(val1 - val2, somethingElse);
var items = collection.Where(i => Min(min, item.Property1) > i.Property2)
于 2012-06-27T19:35:11.923 回答
1

如果val1 - val2并且somethingElse不依赖于item,您可以做一个简单的技巧:

var tempMin = Math.Min(val1-val2, somethingElse);
from item in collection where
     Math.Min(item.Property1, tempMin) > item.Property2
     select item;

否则,你可以去

from item in collection where
     Math.Min(item.Property1, Math.Min(val1-val2, somethingElse)) > item.Property2
     select item;

如果要比较的项目数量可能很大或事先不知道,您可以使用 Lee 的版本。

于 2012-06-27T19:41:57.127 回答
0

您当然可以通过Min以下方式使用扩展方法:

from item in collection where
(new[] { val1-val2, item.Property1, somethingElse }.Min()) > item.Property2
select item;

但是,这将导致为 a 中的每个实例化一个新item数组collection。就性能而言,这可能不是最好的方法。最好编写一个简单的方法来获得三个值中的最小值:

public double Min(double a, double b, double c)
{
    double result = a;

    if (result < b)
    {
       result = b;
    }

    if (result < c)
    {
       result = c;
    }

    return result;
}

然后,您可以编写以下查询:

from item in collection where
Min(val1-val2, item.Property1, somethingElse) > item.Property2
select item;
于 2012-06-27T19:39:26.033 回答