C#中利用Expression表达式树进行多个Lambda表达式合并
生活随笔
收集整理的這篇文章主要介紹了
C#中利用Expression表达式树进行多个Lambda表达式合并
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在上一文中介紹使用了合并兩個Lambda表達式,能兩個就能多個,代碼如下圖所示:
public static class ExpressionHelp{private static Expression<T> Combine<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge){MyExpressionVisitor visitor = new MyExpressionVisitor(first.Parameters[0]);Expression bodyone = visitor.Visit(first.Body);Expression bodytwo = visitor.Visit(second.Body);return Expression.Lambda<T>(merge(bodyone,bodytwo),first.Parameters[0]);}public static Expression<Func<T, bool>> ExpressionAnd<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second){return first.Combine(second, Expression.And);}public static Expression<Func<T, bool>> ExpressionOr<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second){return first.Combine(second, Expression.Or);}}public class MyExpressionVisitor : ExpressionVisitor{public ParameterExpression _Parameter { get; set; }public MyExpressionVisitor(ParameterExpression Parameter){_Parameter = Parameter;}protected override Expression VisitParameter(ParameterExpression p){return _Parameter;}public override Expression Visit(Expression node){return base.Visit(node);//Visit會根據VisitParameter()方法返回的Expression修改這里的node變量}}?假設存在如下數據集合:
public class Person{public string Name { get; set; }public string Gender { get; set; }public int Age { get; set; }public List<Phone> Phones { get; set; }}List<Person> PersonLists = new List<Person>(){new Person { Name = "張三",Age = 20,Gender = "男",Phones = new List<Phone> {new Phone { Country = "中國", City = "北京", Name = "小米" },new Phone { Country = "中國",City = "北京",Name = "華為"},new Phone { Country = "中國",City = "北京",Name = "聯想"},new Phone { Country = "中國",City = "臺北",Name = "魅族"},}},new Person { Name = "松下",Age = 30,Gender = "男",Phones = new List<Phone> {new Phone { Country = "日本",City = "東京",Name = "索尼"},new Phone { Country = "日本",City = "大阪",Name = "夏普"},new Phone { Country = "日本",City = "東京",Name = "松下"},}},new Person { Name = "克里斯",Age = 40,Gender = "男",Phones = new List<Phone> {new Phone { Country = "美國",City = "加州",Name = "蘋果"},new Phone { Country = "美國",City = "華盛頓",Name = "三星"},new Phone { Country = "美國",City = "華盛頓",Name = "HTC"}}}};And操作使用如下圖所示:
Expression<Func<Person, bool>> expression = ex => ex.Age == 30; expression = expression.ExpressionAnd(t => t.Name.Equals("松下")); var Lists = PersonLists.Where(expression.Compile()); foreach (var List in Lists) {Console.WriteLine(List.Name); } Console.Read();Or操作使用如下圖所示:
Expression<Func<Person, bool>> expression = ex => ex.Age == 20; expression = expression.ExpressionOr(t => t.Name.Equals("松下")); var Lists = PersonLists.Where(expression.Compile()); foreach (var List in Lists) {Console.WriteLine(List.Name); } Console.Read();?
總結
以上是生活随笔為你收集整理的C#中利用Expression表达式树进行多个Lambda表达式合并的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 初探EntityFramework——空
- 下一篇: C#中的修饰符及其说明