LinqExtension.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System;
  2. using System.Linq.Expressions;
  3. namespace Masuit.Tools.Core.Linq
  4. {
  5. /// <summary>
  6. /// linq扩展类
  7. /// </summary>
  8. public static class LinqExtension
  9. {
  10. /// <summary>
  11. /// 与连接
  12. /// </summary>
  13. /// <typeparam name="T"></typeparam>
  14. /// <param name="left">左条件</param>
  15. /// <param name="right">右条件</param>
  16. /// <returns></returns>
  17. public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> left, Expression<Func<T, bool>> right)
  18. {
  19. var dateExpr = Expression.Parameter(typeof(T));
  20. var parameterReplacer = new ParameterReplacer(dateExpr);
  21. var leftwhere = parameterReplacer.Replace(left.Body);
  22. var rightwhere = parameterReplacer.Replace(right.Body);
  23. var body = Expression.And(leftwhere, rightwhere);
  24. return Expression.Lambda<Func<T, bool>>(body, dateExpr);
  25. }
  26. /// <summary>
  27. /// 或连接
  28. /// </summary>
  29. /// <typeparam name="T"></typeparam>
  30. /// <param name="left">左条件</param>
  31. /// <param name="right">右条件</param>
  32. /// <returns></returns>
  33. public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> left, Expression<Func<T, bool>> right)
  34. {
  35. var dateExpr = Expression.Parameter(typeof(T));
  36. var parameterReplacer = new ParameterReplacer(dateExpr);
  37. var leftwhere = parameterReplacer.Replace(left.Body);
  38. var rightwhere = parameterReplacer.Replace(right.Body);
  39. var body = Expression.Or(leftwhere, rightwhere);
  40. return Expression.Lambda<Func<T, bool>>(body, dateExpr);
  41. }
  42. }
  43. }