How to convert Func to Predicate?

前端 未结 4 2053
离开以前
离开以前 2020-12-01 12:34

Yes I\'ve seen this but I couldn\'t find the answer to my specific question.

Given a lambda testLambda that takes T and returns a boolean (I can mak

相关标签:
4条回答
  • 2020-12-01 12:45

    Sound like a case for

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

    I love C#3 ...

    0 讨论(0)
  • 2020-12-01 12:48

    I'm a little late to the game, but I like extension methods:

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

    Then you can use it like:

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

    Hmm, I now see the FindIndex extension method. This is a little more general answer I guess. Not really much different from the ConvertToPredicate either.

    0 讨论(0)
  • 2020-12-01 12:55

    Easy:

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

    Basically you can create a new delegate instance with any compatible existing instance. This also supports variance (co- and 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);
    

    If you want to make it generic:

    static Predicate<T> ConvertToPredicate<T>(Func<T, bool> func)
    {
        return new Predicate<T>(func);
    }
    
    0 讨论(0)
  • 2020-12-01 13:06

    I got this:

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

    Works, but ick.

    0 讨论(0)
提交回复
热议问题