C# 如何将 Func<T, bool> 转换为 Predicate<T>?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/731249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert Func<T, bool> to Predicate<T>?
提问by George Mauer
Yes I've seen thisbut I couldn't find the answer to my specific question.
是的,我见过这个,但我找不到我的具体问题的答案。
Given a lambda testLambdathat takes T and returns a boolean (I can make it either Predicate or Func that's up to me)
给定一个接受 T 并返回一个布尔值的 lambda testLambda(我可以将它设为 Predicate 或 Func,这取决于我)
I need to be able to use both List.FindIndex(testLambda) (takes a Predicate) and List.Where(testLambda) (takes a Func).
我需要能够同时使用 List.FindIndex(testLambda)(采用谓词)和 List.Where(testLambda)(采用 Func)。
Any ideas how to do both?
任何想法如何做到这两点?
采纳答案by Jon Skeet
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 compatibleexisting instance. This also supports variance (co- and contra-):
基本上,您可以使用任何兼容的现有实例创建一个新的委托实例。这也支持方差(co-和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);
}
回答by George Mauer
I got this:
我懂了:
Func<object, bool> testLambda = x=>true;
int idx = myList.FindIndex(x => testLambda(x));
Works, but ick.
有效,但很糟糕。
回答by MartinStettner
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 ...
我喜欢 C#3 ...
回答by Michael Welch
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.
嗯,我现在看到了 FindIndex 扩展方法。我猜这是一个更一般的答案。与 ConvertToPredicate 也没有太大区别。