如何将Func 转换为Predicate ?

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

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

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

任何想法如何做到两个?

简单:

Func func = x => x.Length > 5; Predicate predicate = new Predicate(func); 

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

 Action actOnObject = x => Console.WriteLine(x); Action actOnString = new Action(actOnObject); Func returnsString = () => "hi"; Func returnsObject = new Func(returnsString); 

如果你想使它通用:

 static Predicate ConvertToPredicate(Func func) { return new Predicate(func); } 

我懂了:

 Func testLambda = x=>true; int idx = myList.FindIndex(x => testLambda(x)); 

工作,但ick。

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

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

然后你就可以使用它:

 List list = new List { 1, 3, 4, 5, 7, 9 }; Func isEvenFunc = x => x % 2 == 0; var index = list.FindIndex(isEvenFunc.ToPredicate()); 

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

听起来像一个案例

 static class ListExtensions { public static int FindIndex(this List list, Func f) { return list.FindIndex(x => f(x)); } } // ... Func f = x=>Something(x); MyList.FindIndex(f); // ... 

我喜欢C#3 ……