LINQ:有没有办法为where子句提供带有多个参数的谓词

hon*_*pei 5 c# linq where

想知道是否有办法执行以下操作:我基本上想要为具有多个参数的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
}
Run Code Online (Sandbox Code Playgroud)

Zbi*_*iew 8

var result = items.Where(i => Predicate(i, obj));
Run Code Online (Sandbox Code Playgroud)


Eri*_*ert 5

您想要的操作称为"部分评估"; 它在逻辑上与将两参数函数"卷曲"成两个单参数函数有关.

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);
Run Code Online (Sandbox Code Playgroud)

现在你可以isGreaterThanTwo在一个where条款中使用.

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

合理?

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

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

现在你可以做一个工厂:

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
Run Code Online (Sandbox Code Playgroud)

这一切都清楚了吗?