【发布时间】:2010-10-18 09:22:58
【问题描述】:
是的,我见过this,但我找不到具体问题的答案。
给定一个接受 T 并返回布尔值的 lambda testLambda(我可以将其设为 Predicate 或 Func,这取决于我)
我需要能够同时使用 List.FindIndex(testLambda)(接受谓词)和 List.Where(testLambda)(接受 Func)。
有什么想法可以同时做到吗?
【问题讨论】:
是的,我见过this,但我找不到具体问题的答案。
给定一个接受 T 并返回布尔值的 lambda testLambda(我可以将其设为 Predicate 或 Func,这取决于我)
我需要能够同时使用 List.FindIndex(testLambda)(接受谓词)和 List.Where(testLambda)(接受 Func)。
有什么想法可以同时做到吗?
【问题讨论】:
我知道了:
Func<object, bool> testLambda = x=>true;
int idx = myList.FindIndex(x => testLambda(x));
有效,但不错。
【讨论】:
简单:
Func<string,bool> func = x => x.Length > 5;
Predicate<string> predicate = new Predicate<string>(func);
基本上你可以用任何现有的兼容实例创建一个新的委托实例。这也支持方差(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);
如果你想让它通用:
static Predicate<T> ConvertToPredicate<T>(Func<T, bool> func)
{
return new Predicate<T>(func);
}
【讨论】:
听起来像一个案例
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);
// ...
我喜欢 C#3 ...
【讨论】:
我玩的有点晚了,但我喜欢扩展方法:
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 也没有太大区别。
【讨论】: