How to convert Func to Predicate?

前端 未结 4 2052
离开以前
离开以前 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:48

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

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

    Then you can use it like:

    List list = new List { 1, 3, 4, 5, 7, 9 };
    Func 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.

提交回复
热议问题