合并两个 Lambda 表达式

概述

  在开发工作中,有些时候需要对一些增删改查进行封装(用 Lambda 表达式来筛选数据),但是又有一部分条件总是相同的,对于相同的部分可以直接写到方法里,而不同的部分作为参数传进去。

定义扩展方法:

  public static class Ext    
  {        
      public static Expression<Func<T, bool>> AndAlso<T>(  this Expression<Func<T, bool>> a,  Expression<Func<T, bool>> b)        
      {            
          var p = Expression.Parameter(typeof(T), "x");            
          var bd = Expression.AndAlso(Expression.Invoke(a, p), Expression.Invoke(b, p));            
          var ld = Expression.Lambda<Func<T, bool>>(bd, p);            
          return ld;        
      }    
  }

定义 Person 类

    class Person
    {
        /// <summary>
        /// 性别
        /// </summary>
        public string Sex { get; set; }
        /// <summary>
        /// 年龄
        /// </summary>
        public int Age { get; set; }
        /// <summary>
        /// 身高
        /// </summary>
        public int Height { get; set; }
    }

扩展方法调用

            List<Person> persons = new List<Person>()
            {
                new Person{ Sex = "", Age = 22, Height = 175},
                new Person{ Sex = "", Age = 25, Height = 176},
                new Person{ Sex = "", Age = 19, Height = 175},
                new Person{ Sex = "", Age = 21, Height = 172},
                new Person{ Sex = "", Age = 20, Height = 168}
            };

            Expression<Func<Person, bool>> e1 = p => p.Age >= 21 && p.Sex == "";
            Expression<Func<Person, bool>> e2 = p => p.Height > 170;

            Expression<Func<Person, bool>> e3 = e1.AndAlso(e2);
            var ls = persons.Where(e3.Compile()).ToList();

扩展使用

  在上述例子中,通过扩展方法可以进行以下使用:封装一个方法,参数类型为 Expression<Func<Person, bool>> ,然后,将 e2、e3 及查询过程封装到方法里面,这样查询的时候只需要传入参数 “p => p.Age >= 21 && p.Sex == "男"”就可以实现上述实例中的查询。

猜你喜欢

转载自www.cnblogs.com/zhangchaoran/p/10217982.html
今日推荐