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

C#ExpressionPredicate

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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;

Solution 2 - C#

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;

Solution 3 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLance FisherView Question on Stackoverflow
Solution 1 - C#Sam HarwellView Answer on Stackoverflow
Solution 2 - C#Jon SkeetView Answer on Stackoverflow
Solution 3 - C#tvanfossonView Answer on Stackoverflow