简体   繁体   English

如何转换Func <T, bool> 谓词 <T> ?

[英]How to convert Func<T, bool> to Predicate<T>?

Yes I've seen this but I couldn't find the answer to my specific question. 是的我见过这个,但我找不到我的具体问题的答案。

Given a lambda testLambda that takes T and returns a boolean (I can make it either Predicate or Func that's up to me) 给定一个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? 任何想法如何做到两个?

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 compatible existing instance. 基本上,您可以使用任何兼容的现有实例创建新的委托实例。 This also supports variance (co- and 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);
}

I got this: 我懂了:

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

Works, but ick. 工作,但ick。

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. 嗯,我现在看到FindIndex扩展方法。 This is a little more general answer I guess. 我猜这是一个更普遍的答案。 Not really much different from the ConvertToPredicate either. 与ConvertToPredicate没有太大区别。

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 ......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM