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

こ雲淡風輕ζ 提交于 2019-12-02 15:24:53
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;

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

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;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!