How to convert an Expression<Func<T, bool>> to a Predicate<T>
Asked Answered
C

3

63

I have a method that accepts an Expression<Func<T, bool>> as a parameter. I would like to use it as a predicate in the List.Find() method, but I can't seem to convert it to a Predicate which List takes. Do you know a simple way to do this?

public IList<T> Find<T>(Expression<Func<T, bool>> expression) where T : class, new()
{
    var list = GetList<T>();

    var predicate = [what goes here to convert expression?];

    return list.Find(predicate);
}

Update

Combining answers from tvanfosson and 280Z28, I am now using this:

public IList<T> Find<T>(Expression<Func<T, bool>> expression) where T : class, new()
{
    var list = GetList<T>();

    return list.Where(expression.Compile()).ToList();
}
Chloride answered 1/8, 2009 at 23:18 Comment(0)
E
85
Func<T, bool> func = expression.Compile();
Predicate<T> pred = t => func(t);

Edit: per the comments we have a better answer for the second line:

Predicate<T> pred = func.Invoke;
Evangelist answered 1/8, 2009 at 23:20 Comment(1)
Yeah, func.Invoke looks better.Chloride
D
38

Another options which hasn't been mentioned:

Func<T, bool> func = expression.Compile();
Predicate<T> predicate = new Predicate<T>(func);

This generates the same IL as

Func<T, bool> func = expression.Compile();
Predicate<T> predicate = func.Invoke;
Deicide answered 2/8, 2009 at 6:18 Comment(1)
why this only has 12 votes? you ungrateful peasants! It is he, Jon Skeet. Heed his words!!!!Cw
P
29

I'm not seeing the need for this method. Just use Where().

 var sublist = list.Where( expression.Compile() ).ToList();

Or even better, define the expression as a lambda inline.

 var sublist = list.Where( l => l.ID == id ).ToList();
Phalanger answered 1/8, 2009 at 23:21 Comment(3)
Using Where() instead of Find() is what I needed to do. However your first example needs to use expression.Compile() instead of just expression. Thanks.Chloride
Updated. I neglected the fact that Where takes a Func<T,bool>.Phalanger
acctually you can use var sublist = list.Where(expression);Bramwell

© 2022 - 2024 — McMap. All rights reserved.