合并表达式列表中的表达式

3

我希望使用LINQ to SQL创建动态查询构建器。

为了实现这一点,我创建了我的接口,用于添加每个动态条件。

List<Expression<Func<T,bool>>>

接口看起来像:

public interface IExpression<T>
{
    IExpression<T> AddWhere(Expression<Func<T,bool>> whereCriteria);    
}

现在我想将列表中的所有表达式组合起来,并使用“and”条件构建where子句并执行查询。
我尝试过组合表达式,但没有成功。
请问有人可以帮忙吗?或者请提出其他建议。
1个回答

7
最简单的方法是使用PredicateBuilder:http://www.albahari.com/nutshell/predicatebuilder.aspx 基本上,您需要使用此辅助类:
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;

public static class PredicateBuilder
{
  public static Expression<Func<T, bool>> True<T> ()  { return f => true;  }
  public static Expression<Func<T, bool>> False<T> () { return f => false; }

  public static Expression<Func<T, bool>> Or<T> (this Expression<Func<T, bool>> expr1,
                                                      Expression<Func<T, bool>> expr2)
  {
    var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());
    return Expression.Lambda<Func<T, bool>>
          (Expression.OrElse (expr1.Body, invokedExpr), expr1.Parameters);
  }

  public static Expression<Func<T, bool>> And<T> (this Expression<Func<T, bool>> expr1,
                                                       Expression<Func<T, bool>> expr2)
  {
    var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());
    return Expression.Lambda<Func<T, bool>>
          (Expression.AndAlso (expr1.Body, invokedExpr), expr1.Parameters);
  }
}

然后你可以这样使用它:
  public static Expression<Func<Product, bool>> ContainsInDescription (
                                                params string[] keywords)
  {
    var predicate = PredicateBuilder.False<Product>();
    foreach (string keyword in keywords)
    {
      string temp = keyword;
      predicate = predicate.Or (p => p.Description.Contains (temp));
    }
    return predicate;
  }

这段代码和示例都来自上面提供的链接,我把它放在这里以防万一链接失效。

你的情况有点复杂,因为你的接口不使用泛型。你能展示更多相关代码吗?这样我就能更好地根据你的实际需求来调整解决方案。


谢谢回复。我正在研究提供的链接。我的接口使用泛型。我已经进行了修改。 - nppatel
@user2249600:如果是这样的话,那么这应该只是一个简单的复制粘贴问题。请注意,在对值进行“与”操作时,您应该使用PredicateBuilder.True<T>()来初始化谓词。 - Luaan
太棒了!我不明白为什么这个没有更多的赞。 - CthenB
这方面还有一篇很棒的文章可以在code project上找到。 - RajeshKdev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接