繁体   English   中英

如何从多个表达式的并集组成表达式树?

[英]How can I compose an expression tree from the union of several expressions?

我正在尝试构建一个IQueryable ,它将由我的实体 model 评估。 我想将两组 lambdas 传递给它,并让它将所有内容组合成一个更复杂的表达式树,然后将其传递给数据库以执行。

这是我到目前为止所拥有的:

public class FilterManager<T>
{
    public List<Expression<Func<T, bool>>> Inclusive { get; set; }
    public List<Expression<Func<T, bool>>> Exclusive { get; set; }

    public IQueryable<T> ApplyFilters(IQueryable<T> query)
    {
        var q = query;

        Exclusive.ForEach(exp => q = q.Where(exp)); //works fine
        Inclusive.ForEach(exp => /* ??? */); 

        return q;
    }

    //ctor, etc.
}

这里的想法是我将几个 Expression 添加到Inclusive ,它们将它们“Ors”在一起。 例如,如果Tint ,则代码:

fm.Inclusive.Add(x => x > 1);
fm.Inclusive.Add(y => y < 5);

query = fm.ApplyFilters(query);

应该具有与以下相同的结果集:

query = query.Where(z => z > 1 || z < 5);

在没有 PredicateBuilder 等第三方工具的情况下,如何让Inclusive工作? 第三方工具通常很好,但我想提高我对如何在 .NET 中编写表达式的理解。

我还需要确保树不会被评估,以便我可以对数据库进行过滤。 这意味着我需要生成 Entity Framework 4.0 可以使用的东西。

我能想到的最接近的匹配是:

public IQueryable<T> ApplyFilters(IQueryable<T> query)
{
    IQueryable<T> q;

    if (!Inclusive.Any())
        q = query;
    else
    {
        q = Enumerable.Empty<T>();
        Inclusive.ForEach(exp => q = q.Union(query.Where(exp)));
    }

    Exclusive.ForEach(exp => q = q.Where(exp));

    return q;
}

但我几乎可以肯定这将非常低效

试试这样的东西? 我不确定我没有测试过。

Inclusive.ForEach(exp => q = q.Union(q.Where(exp)));

即使已经有一个公认的答案,我想指出您可以使用谓词构建器将表达式与Or结合起来。 这将保持它作为对数据库的简单查询。

http://www.albahari.com/nutshell/predicatebuilder.aspx

我还没有在我的实体 model 上对其进行测试,所以我不知道 EF 是否会支持它,但以下适用于 L2O。 这只是与Snowbear JIM-compiler的代码略有不同:

public IQueryable<T> ApplyFilters(IQueryable<T> query)
{
    Exclusive.ForEach(exp => query = query.Where(exp));

    if (Inclusive.Count == 0)
    {
        return query;
    }

    IQueryable<T> q = Enumerable.Empty<T>().AsQueryable<T>();
    Inclusive.ForEach(exp => q = q.Union(query.Where(exp)));

    return q;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM