在上一文中介绍使用了合并两个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表达式有效地合并。通过示例代码展示了如何进行And和Or操作,从而实现对数据集合的复杂条件过滤。
238





