How to convert an Expression> to a Predicate

前端 未结 3 1049
醉话见心
醉话见心 2021-01-30 10:32

I have a method that accepts an Expression> as a parameter. I would like to use it as a predicate in the List.Find() method, but I can\'t

相关标签:
3条回答
  • 2021-01-30 10:52

    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();
    
    0 讨论(0)
  • 2021-01-30 10:58

    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;
    
    0 讨论(0)
  • 2021-01-30 11:05
    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;
    
    0 讨论(0)
提交回复
热议问题