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

必要な操作は「部分評価」と呼ばれます。これは、2 パラメーター関数を 2 つの 1 パラメーター関数に「カリー化」することに論理的に関連しています。

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);

isGreaterThanTwoこれで、where節で使用できます。

最初の引数を指定したい場合は、簡単に書くことができます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 に答える