1. 程式人生 > >合併兩個 Lambda 表示式

合併兩個 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 == "男"”就可以實現上述例項中的查詢。