5

想知道是否有办法执行以下操作:我基本上想为 where 子句提供一个谓词,其中包含多个参数,如下所示:

public bool Predicate (string a, object obj)
{
  // blah blah    
}

public void Test()
{
    var obj = "Object";
    var items = new string[]{"a", "b", "c"};
    var result = items.Where(Predicate); // here I want to somehow supply obj to Predicate as the second argument
}
4

3 回答 3

8
var result = items.Where(i => Predicate(i, obj));
于 2013-01-17T17:52:47.057 回答
6

您想要的操作称为“部分评估”;它在逻辑上与将一个二参数函数“柯里化”为两个一参数函数有关。

static class Extensions
{
  static Func<A, R> PartiallyEvaluateRight<A, B, R>(this Func<A, B, R> f, B b)
  {
    return a => f(a, b);
  }
}
...
Func<int, int, bool> isGreater = (x, y) => x > y;
Func<int, bool> isGreaterThanTwo = isGreater.PartiallyEvaluateRight(2);

现在您可以isGreaterThanTwowhere子句中使用。

如果您想提供第一个参数,那么您可以轻松编写PartiallyEvaluateLeft.

有道理?

柯里化操作(部分适用于左边)通常写成:

static class Extensions
{
  static Func<A, Func<B, R>> Curry<A, B, R>(this Func<A, B, R> f)
  {
    return a => b => f(a, b);
  }
}

现在你可以创建一个工厂:

Func<int, int, bool> greaterThan = (x, y) => x > y;
Func<int, Func<int, bool>> factory = greaterThan.Curry();
Func<int, bool> withTwo = factory(2); // makes y => 2 > y

这一切都清楚了吗?

于 2013-01-17T18:11:42.233 回答
3

你期待这样的事情吗

        public bool Predicate (string a, object obj)
        {
          // blah blah    
        }

        public void Test()
        {
            var obj = "Object";
            var items = new string[]{"a", "b", "c"};
            var result = items.Where(x => Predicate(x, obj)); // here I want to somehow supply obj to Predicate as the second argument
        }
于 2013-01-17T17:53:10.173 回答