首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将Func<T,bool>转换为Predicate<T>?

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

Stack Overflow用户
提问于 2009-04-08 18:29:41
回答 4查看 16.7K关注 0票数 28

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

给定一个采用T并返回布尔值的λtestLambda (我可以将其设为谓词或函数,由我决定)

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

有没有办法同时做到这两点?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2009-04-08 18:31:49

简单:

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

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

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);
}
票数 58
EN

Stack Overflow用户

发布于 2009-04-08 18:31:45

我得到了这个:

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

行得通,但很讨厌。

票数 10
EN

Stack Overflow用户

发布于 2011-07-07 23:48:22

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

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的区别也不是很大。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/731249

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档