ExpressionBuilder.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Linq.Expressions;
  6. using System.Configuration;
  7. using System.Data.SqlClient;
  8. namespace Bowin.Common.Linq
  9. {
  10. public static class ExpressionBuilder
  11. {
  12. public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
  13. {
  14. return first.Compose<Func<T, bool>>(second, new Func<Expression, Expression, Expression>(Expression.And));
  15. }
  16. public static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge)
  17. {
  18. Expression expression = ParameterRebinder.ReplaceParameters(
  19. first.Parameters.Zip(
  20. second.Parameters,
  21. (f, s) => new
  22. {
  23. First = f,
  24. Second = s
  25. }).ToDictionary(p => p.Second, p => p.First),
  26. second.Body);
  27. return Expression.Lambda<T>(merge(first.Body, expression), first.Parameters);
  28. }
  29. public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
  30. {
  31. return first.Compose<Func<T, bool>>(second, new Func<Expression, Expression, Expression>(Expression.Or));
  32. }
  33. }
  34. }