簡體   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