简体   繁体   English

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

[英]LINQ: is there a way to supply a predicate with more than one parameter to where clause

wondering if there is a way to do the following: I basically want to supply a predicate to a where clause with more than one paremeters like the following: 想知道是否有办法执行以下操作:我基本上想要为具有多个参数的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
}
var result = items.Where(i => Predicate(i, obj));

The operation you want is called "partial evaluation"; 您想要的操作称为“部分评估”; it is logically related to "currying" a two-parameter function into two one-parameter functions. 它在逻辑上与将两参数函数“卷曲”成两个单参数函数有关。

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

And now you can use isGreaterThanTwo in a where clause. 现在你可以在where子句中使用isGreaterThanTwo

If you wanted to supply the first argument then you could easily write PartiallyEvaluateLeft . 如果您想提供第一个参数,那么您可以轻松编写PartiallyEvaluateLeft

Make sense? 合理?

The currying operation (which partially applies to the left) is usually written: 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);
  }
}

And now you can make a factory: 现在你可以做一个工厂:

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

Is that all clear? 这一切都清楚了吗?

Do you expect something like this 你期待这样的事吗?

        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
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM