代码之家  ›  专栏  ›  技术社区  ›  simonalexander2005

以委托代替谓词的迭代器

  •  0
  • simonalexander2005  · 技术社区  · 7 年前

    我知道我可以定义一个谓词:

    Dim _predicate As New Func(Of T, Boolean)(Function(e)e.Foo= "Value")
    

    并将其传递给LINQ方法:

    Dim _x as String = enumerable.First(predicate).Foo
    

    我想抽象出“Value”字符串,所以我创建了:

    Dim _delegate As New Func(Of T, String, Boolean)(Function(e, s)e.Foo= s)
    

    如何将此委托传递给LINQ函数,传递字符串参数,但仍让它假定每次T参数都是迭代器项?

    我想没有可以接受这样一个委托的重载,但我真的不想为所有LINQ方法编写自己的重载。。。

    我想我想要的是一种内联方式,将委托转换为谓词,提供替换额外参数的值。

    1 回复  |  直到 7 年前
        1
  •  1
  •   vc 74    7 年前

    抱歉,我不是VB专业的人,但我相信我的代码可以很容易地翻译:

    class ValueFilter<T>
      where T : IFooThing
    {
      public ValueFilter(string value)
      {
        _value = value;
      }
      private readonly string _value;
    
      public IsMatch(T item) => (item.Foo == _value);
    }
    

    然后

    var filter = new ValueFilter("A value");
    
    IEnumerable<Foo> collection = ...
    collection.First(filter.IsMatch);
    

    (假设 IFooThing 有一个 public string Foo { get; } 所有物