首先是2个相同的类
class ClassA { public int Id { get; set; } public string Name { get; set; } } class ClassB { public int Id { get; set; } public string Name { get; set; } }
然后自定义访问者,将 ParameterExpression全部换成另一个类的
public class MyVisitor<SourceT,DescT> : ExpressionVisitor { private readonly ParameterExpression DescTParameter = Expression.Parameter(typeof(DescT), "p"); protected override Expression VisitParameter(ParameterExpression node) { if (node.Type == typeof(SourceT)) { return DescTParameter; } return base.VisitParameter(node); } protected override Expression VisitMember(MemberExpression node) { if (node.Member.ReflectedType == typeof(SourceT)) { var idExpression = Expression.Property(DescTParameter, node.Member.Name); return idExpression; } return base.VisitMember(node); } public Expression<Func<DescT, bool>> Modify(Expression<Func<SourceT, bool>> expression) { var result = this.Visit(expression.Body); return Expression.Lambda<Func<DescT, bool>>(result, DescTParameter); } }
调用代码如下:
var classAList = new List<ClassA> { new ClassA {Id = 1, Name = "User1"}, new ClassA {Id = 2, Name = "User2"} }; Expression<Func<ClassB, bool>> expressionB = p => p.Id > 1 && p.Name == "User2";
MyVisitor<ClassB,ClassA> visitor =new MyVisitor<ClassB, ClassA>(); var ex = visitor.Modify(expressionB); var result = classAList.AsQueryable().Where(ex); foreach (var item in result) { Console.WriteLine(item.Name); }