George Mauer
George Mauer

Reputation: 122202

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?

Upvotes: 31

Views: 18828

Answers (4)

Michael Welch
Michael Welch

Reputation: 1784

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. This is a little more general answer I guess. Not really much different from the ConvertToPredicate either.

Upvotes: 5

MartinStettner
MartinStettner

Reputation: 29184

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

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502786

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);
}

Upvotes: 66

George Mauer
George Mauer

Reputation: 122202

I got this:

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

Works, but ick.

Upvotes: 10

Related Questions