Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

I need to be able to use both List.FindIndex(testLambda) (takes a Predicate) and List.Where(testLambda) (takes a Func).

Any ideas how to do both?

like image 948
George Mauer Avatar asked Apr 08 '09 18:04

George Mauer


People also ask

What is Predicate T?

Predicate<T> is a functional construct providing a convenient way of basically testing if something is true of a given T object. For example suppose I have a class: class Person { public string Name { get; set; } public int Age { get; set; } }

What is Predicate in c#?

Predicate is the delegate like Func and Action delegates. It represents a method containing a set of criteria and checks whether the passed parameter meets those criteria. A predicate delegate methods must take one input parameter and return a boolean - true or false.

How does Func work c#?

Func is a delegate that points to a method that accepts one or more arguments and returns a value. Action is a delegate that points to a method which in turn accepts one or more arguments but returns no value. In other words, you should use Action when your delegate points to a method that returns void.


2 Answers

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); } 
like image 140
Jon Skeet Avatar answered Sep 30 '22 00:09

Jon Skeet


I got this:

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

Works, but ick.

like image 35
George Mauer Avatar answered Sep 29 '22 22:09

George Mauer