繁体   English   中英

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

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

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

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

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

现在你可以在where子句中使用isGreaterThanTwo

如果您想提供第一个参数,那么您可以轻松编写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);
  }
}

现在你可以做一个工厂:

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

这一切都清楚了吗?

你期待这样的事吗?

        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