您的位置:首页 > 编程语言 > C#

C#中利用Expression表达式树进行多个Lambda表达式合并

2019-06-17 14:45 344 查看

上一文中介绍使用了合并两个Lambda表达式,能两个就能多个,代码如下图所示:

[code]    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变量
}
}

 假设存在如下数据集合:

[code]    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操作使用如下图所示:

[code]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操作使用如下图所示:

[code]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();

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: