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?
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; } }
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With