如何转换的表达式来; Func键< T,BOOL>>到谓词< T> [英] How to convert an Expression<Func<T, bool>> to a Predicate<T>

查看:193
本文介绍了如何转换的表达式来; Func键< T,BOOL>>到谓词< T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接受表达式来的方法; Func键< T,BOOL>> 作为参数。我想用它作为List.Find()方法的谓语,但我似乎无法将其转换为一个谓词哪个列表重视。你知道一个简单的方法来做到这一点。



 公开的IList< T>查找和LT; T>(表达式来; Func键< T,BOOL>>表达式)其中T:类,新的()
{
无功名单=的GetList< T>();

VAR谓词= [发生的事情在这里转换体现在哪里?]

返回list.Find(谓语);
}



更新



组合从tvanfosson和280Z28答案,我现在用这样的:

 公开的IList< T>查找和LT; T>(表达式来; Func键< T,BOOL>>表达式)其中T:类,新的()
{
无功名单=的GetList< T>();

返回list.Where(expression.Compile())了ToList();
}


解决方案

  Func键< T,BOOL> FUNC = expression.Compile(); 
谓< T>预计值= T => FUNC(T);



编辑:按照意见,我们有第二行更好的答案:

 谓词< T>预计值= func.Invoke; 


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

解决方案

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;

这篇关于如何转换的表达式来; Func键&LT; T,BOOL&GT;&GT;到谓词&LT; T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆