如何将Func <T,bool>转换为Predicate <T>?

Geo*_*uer 19 c# lambda .net-3.5

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

给定一个lambda testLambda,它接受一个布尔值(我可以使它成为Predicate或Func,这取决于我)

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

任何想法如何做到两个?

Jon*_*eet 48

简单:

Func<string,bool> func = x => x.Length > 5;
Predicate<string> predicate = new Predicate<string>(func);
Run Code Online (Sandbox Code Playgroud)

基本上,您可以使用任何兼容的现有实例创建新的委托实例.这也支持方差(共同和反对):

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);
Run Code Online (Sandbox Code Playgroud)

如果你想让它通用:

static Predicate<T> ConvertToPredicate<T>(Func<T, bool> func)
{
    return new Predicate<T>(func);
}
Run Code Online (Sandbox Code Playgroud)

  • 这些游戏让我很生气.我想我明白为什么他们这样做但仍然...... (5认同)
  • 究竟.向后兼容性是一个*大问题. (2认同)

Geo*_*uer 10

我懂了:

Func<object, bool> testLambda = x=>true;
int idx = myList.FindIndex(x => testLambda(x));
Run Code Online (Sandbox Code Playgroud)

工作,但ick.


Mic*_*lch 5

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

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

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

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());
Run Code Online (Sandbox Code Playgroud)

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