【问题标题】:How to convert an Expression<Func<T, bool>> to a Predicate<T>如何将 Expression<Func<T, bool>> 转换为 Predicate<T>
【发布时间】:2009-08-01 23:18:58
【问题描述】:

我有一个接受Expression&lt;Func&lt;T, bool&gt;&gt; 作为参数的方法。我想将它用作 List.Find() 方法中的谓词,但我似乎无法将其转换为 List 采用的谓词。你知道一个简单的方法吗?

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

更新

结合 tvanfosson 和 280Z28 的答案,我现在正在使用这个:

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# expression predicate


    【解决方案1】:
    Func<T, bool> func = expression.Compile();
    Predicate<T> pred = t => func(t);
    

    编辑:根据 cmets,我们对第二行有更好的答案:

    Predicate<T> pred = func.Invoke;
    

    【讨论】:

    • 是的,func.Invoke 看起来更好。
    【解决方案2】:

    其他未提及的选项:

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

    这会生成与

    相同的 IL
    Func<T, bool> func = expression.Compile();
    Predicate<T> predicate = func.Invoke;
    

    【讨论】:

    • 为什么只有 12 票?你们这些忘恩负义的农民!是他,乔恩·斯基特。听他的话!!!!
    【解决方案3】:

    我认为不需要这种方法。只需使用 Where()。

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

    或者更好的是,将表达式定义为内联 lambda。

     var sublist = list.Where( l => l.ID == id ).ToList();
    

    【讨论】:

    • 使用 Where() 而不是 Find() 是我需要做的。但是,您的第一个示例需要使用 expression.Compile() 而不仅仅是表达式。谢谢。
    • 已更新。我忽略了 Where 需要 Func 的事实。
    • 其实你可以使用 var sublist = list.Where(expression);
    猜你喜欢
    • 2012-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多