【问题标题】:How to convert Func<T, bool> to Predicate<T>?如何将 Func<T, bool> 转换为 Predicate<T>?
【发布时间】:2010-10-18 09:22:58
【问题描述】:

是的,我见过this,但我找不到具体问题的答案。

给定一个接受 T 并返回布尔值的 lambda testLambda(我可以将其设为 Predicate 或 Func,这取决于我)

我需要能够同时使用 List.FindIndex(testLambda)(接受谓词)和 List.Where(testLambda)(接受 Func)。

有什么想法可以同时做到吗?

【问题讨论】:

    标签: c# .net-3.5 lambda


    【解决方案1】:

    我知道了:

    Func<object, bool> testLambda = x=>true;
    int idx = myList.FindIndex(x => testLambda(x));
    

    有效,但不错。

    【讨论】:

    • 谢谢,你拯救了我的一天
    【解决方案2】:

    简单:

    Func<string,bool> func = x => x.Length > 5;
    Predicate<string> predicate = new Predicate<string>(func);
    

    基本上你可以用任何现有的兼容实例创建一个新的委托实例。这也支持方差(co-和contra-):

    Action<object> actOnObject = x => Console.WriteLine(x);
    Action<string> actOnString = new Action<string>(actOnObject);
    
    Func<string> returnsString = () => "hi";
    Func<object> returnsObject = new Func<object>(returnsString);
    

    如果你想让它通用:

    static Predicate<T> ConvertToPredicate<T>(Func<T, bool> func)
    {
        return new Predicate<T>(func);
    }
    

    【讨论】:

    • 他们至少可以为 FindIndex 提供重载
    • 什么样的“游戏”?什么意思?
    • Predicate 在概念上 == Func 但它们仍然不一样。是的,Predicate 是 .Net 2.0 的东西,但现在它已被弃用,应该有一种方法来做同样的事情。
    • @George:如果他们可以让 Predicate 退役,那将有一种方法可以做事。不幸的是,一些代码是使用它编写的,并且停用这种类型会破坏该代码。
    • 没错。向后兼容性是一个问题。
    【解决方案3】:

    听起来像一个案例

    static class ListExtensions
    {
      public static int FindIndex<T>(this List<T> list, Func<T, bool> f) {
        return list.FindIndex(x => f(x));
      }
    }
    
    // ...
    Func<string, bool> f = x=>Something(x);
    MyList.FindIndex(f);
    // ...
    

    我喜欢 C#3 ...

    【讨论】:

      【解决方案4】:

      我玩的有点晚了,但我喜欢扩展方法:

      public static class FuncHelper
      {
          public static Predicate<T> ToPredicate<T>(this Func<T,bool> f)
          {
              return x => f(x);
          }
      }
      

      然后你可以像这样使用它:

      List<int> list = new List<int> { 1, 3, 4, 5, 7, 9 };
      Func<int, bool> isEvenFunc = x => x % 2 == 0;
      var index = list.FindIndex(isEvenFunc.ToPredicate());
      

      嗯,我现在看到了 FindIndex 扩展方法。我猜这是一个更笼统的答案。与 ConvertToPredicate 也没有太大区别。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多