概述
在開發工作中,有些時候需要對一些增刪改查進行封裝(用 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 == "男"”就可以實現上述實例中的查詢。