如何转换 Func<T, bool>谓词<T>?

如何转换 Func<T, bool>谓词<T>?

问题描述:

是的,我看过这个,但我看不到找到我的具体问题的答案.

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

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

Given a lambda testLambda that takes T and returns a boolean (I can make it either Predicate or Func that's up to me)

我需要能够同时使用 List.FindIndex(testLambda)(采用 Predicate)和 List.Where(testLambda)(采用 Func).

I need to be able to use both List.FindIndex(testLambda) (takes a Predicate) and List.Where(testLambda) (takes a Func).

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

Any ideas how to do both?

简单:

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

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

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

如果你想让它通用:

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