将几个类似的SELECT表达式合并为一个表达式

10

如何将几个相似的SELECT表达式合并为单个表达式?

   private static Expression<Func<Agency, AgencyDTO>> CombineSelectors(params Expression<Func<Agency, AgencyDTO>>[] selectors)
    {

        // ???

        return null;
    }

    private void Query()
    {
        Expression<Func<Agency, AgencyDTO>> selector1 = x => new AgencyDTO { Name = x.Name };
        Expression<Func<Agency, AgencyDTO>> selector2 = x => new AgencyDTO { Phone = x.PhoneNumber };
        Expression<Func<Agency, AgencyDTO>> selector3 = x => new AgencyDTO { Location = x.Locality.Name };
        Expression<Func<Agency, AgencyDTO>> selector4 = x => new AgencyDTO { EmployeeCount = x.Employees.Count() };

        using (RealtyContext context = Session.CreateContext())
        {
            IQueryable<AgencyDTO> agencies = context.Agencies.Select(CombineSelectors(selector3, selector4));

            foreach (AgencyDTO agencyDTO in agencies)
            {
                // do something..;
            }
        }
    }

显示列表中的数据。这是为了避免从数据库加载不必要的字段而必要的。 - Boris Mitchenko
3个回答

20

这不是一个简单的问题;你需要重写所有的表达式——严格来说你可以重复利用其中的大部分,但问题在于每个表达式中都有不同的x(尽管看起来相同),因此你需要使用访问器将所有参数替换为最终的x。幸运的是,在4.0版本中这并不太难。

static void Main() {
    Expression<Func<Agency, AgencyDTO>> selector1 = x => new AgencyDTO { Name = x.Name };
    Expression<Func<Agency, AgencyDTO>> selector2 = x => new AgencyDTO { Phone = x.PhoneNumber };
    Expression<Func<Agency, AgencyDTO>> selector3 = x => new AgencyDTO { Location = x.Locality.Name };
    Expression<Func<Agency, AgencyDTO>> selector4 = x => new AgencyDTO { EmployeeCount = x.Employees.Count() };

    // combine the assignments from the 4 selectors
    var convert = Combine(selector1, selector2, selector3, selector4);

    // sample data
    var orig = new Agency
    {
        Name = "a",
        PhoneNumber = "b",
        Locality = new Location { Name = "c" },
        Employees = new List<Employee> { new Employee(), new Employee() }
    };

    // check it
    var dto = new[] { orig }.AsQueryable().Select(convert).Single();
    Console.WriteLine(dto.Name); // a
    Console.WriteLine(dto.Phone); // b
    Console.WriteLine(dto.Location); // c
    Console.WriteLine(dto.EmployeeCount); // 2
}
static Expression<Func<TSource, TDestination>> Combine<TSource, TDestination>(
    params Expression<Func<TSource, TDestination>>[] selectors)
{
    var zeroth = ((MemberInitExpression)selectors[0].Body);
    var param = selectors[0].Parameters[0];
    List<MemberBinding> bindings = new List<MemberBinding>(zeroth.Bindings.OfType<MemberAssignment>());
    for (int i = 1; i < selectors.Length; i++)
    {
        var memberInit = (MemberInitExpression)selectors[i].Body;
        var replace = new ParameterReplaceVisitor(selectors[i].Parameters[0], param);
        foreach (var binding in memberInit.Bindings.OfType<MemberAssignment>())
        {
            bindings.Add(Expression.Bind(binding.Member,
                replace.VisitAndConvert(binding.Expression, "Combine")));
        }
    }

    return Expression.Lambda<Func<TSource, TDestination>>(
        Expression.MemberInit(zeroth.NewExpression, bindings), param);
}
class ParameterReplaceVisitor : ExpressionVisitor
{
    private readonly ParameterExpression from, to;
    public ParameterReplaceVisitor(ParameterExpression from, ParameterExpression to)
    {
        this.from = from;
        this.to = to;
    }
    protected override Expression VisitParameter(ParameterExpression node)
    {
        return node == from ? to : base.VisitParameter(node);
    }
}

这个代码使用了找到的第一个表达式的构造函数,因此您可能希望检查所有其他的在其相应的NewExpression中是否使用了平凡的构造函数。但我把这留给读者来完成。

编辑:在评论中,@Slaks指出更多的LINQ可以使代码更短。当然他是对的-不过可能有点密集以至于不易阅读:

static Expression<Func<TSource, TDestination>> Combine<TSource, TDestination>(
    params Expression<Func<TSource, TDestination>>[] selectors)
{
    var param = Expression.Parameter(typeof(TSource), "x");
    return Expression.Lambda<Func<TSource, TDestination>>(
        Expression.MemberInit(
            Expression.New(typeof(TDestination).GetConstructor(Type.EmptyTypes)),
            from selector in selectors
            let replace = new ParameterReplaceVisitor(
                  selector.Parameters[0], param)
            from binding in ((MemberInitExpression)selector.Body).Bindings
                  .OfType<MemberAssignment>()
            select Expression.Bind(binding.Member,
                  replace.VisitAndConvert(binding.Expression, "Combine")))
        , param);        
}

写了那么多代码,加个赞。如果用 LINQ 调用和一个新的“Parameter”替换嵌套循环,它可以变得更简单。 - SLaks
@Slaks 可能吧,可能吧。不过它已经足够复杂了 - 读者在更加过程化的布局中理解它的机会可能更大。 - Marc Gravell
@Slaks - 只是为了好玩添加的。 - Marc Gravell
我已经改编了您的代码,它正常运行。但是我想使用像Expression<Func<Agency, object>> selector1 = x => new { Name = x.Name }这样的表达式,而不是Expression<Func<Agency, AgencyDTO>> selector1 = x => new AgencyDTO { Name = x.Name }。我该如何让它与这种匿名类型一起工作?如果使用匿名类型,则此表达式(MemberInitExpression)selector.Body会中断。 - alhpe

1

如果所有选择器都只初始化AgencyDTO对象(就像您的示例一样),您可以将表达式转换为NewExpression实例,然后使用表达式的Members调用Expression.New

您还需要一个ExpressionVisitor,将原始表达式中的ParameterExpression替换为正在创建的表达式的单个ParameterExpression


1
实际上它是MemberInitExpressionNewExpression只是构造函数);虽然可以完成(添加)。 - Marc Gravell

1

如果有人像我一样遇到了类似的用例(我的选择器根据所需详细级别针对不同的类),希望以下内容能帮助到你:

简化场景:

public class BlogSummaryViewModel
{
    public string Name { get; set; }

    public static Expression<Func<Data.Blog, BlogSummaryViewModel>> Map()
    {
        return (i => new BlogSummaryViewModel
        {
            Name = i.Name
        });
    }
}

public class BlogViewModel : BlogSummaryViewModel
{
    public int PostCount { get; set; }

    public static Expression<Func<Data.Blog, BlogViewModel>> Map()
    {
        return (i => new BlogViewModel
        {
            Name = i.Name,
            PostCount = i.Posts.Count()
        });
    }
}

我按照@Marc Gravell提供的解决方案进行了适应:

public static class ExpressionMapExtensions
{
    public static Expression<Func<TSource, TTargetB>> Concat<TSource, TTargetA, TTargetB>(
        this Expression<Func<TSource, TTargetA>> mapA, Expression<Func<TSource, TTargetB>> mapB)
        where TTargetB : TTargetA
    {
        var param = Expression.Parameter(typeof(TSource), "i");

        return Expression.Lambda<Func<TSource, TTargetB>>(
            Expression.MemberInit(
                ((MemberInitExpression)mapB.Body).NewExpression,
                (new LambdaExpression[] { mapA, mapB }).SelectMany(e =>
                {
                    var bindings = ((MemberInitExpression)e.Body).Bindings.OfType<MemberAssignment>();
                    return bindings.Select(b =>
                    {
                        var paramReplacedExp = new ParameterReplaceVisitor(e.Parameters[0], param).VisitAndConvert(b.Expression, "Combine");
                        return Expression.Bind(b.Member, paramReplacedExp);
                    });
                })),
            param);
    }

    private class ParameterReplaceVisitor : ExpressionVisitor
    {
        private readonly ParameterExpression original;
        private readonly ParameterExpression updated;

        public ParameterReplaceVisitor(ParameterExpression original, ParameterExpression updated)
        {
            this.original = original;
            this.updated = updated;
        }

        protected override Expression VisitParameter(ParameterExpression node) => node == original ? updated : base.VisitParameter(node);
    }
}

扩展类的Map方法变为:
    public static Expression<Func<Data.Blog, BlogViewModel>> Map()
    {
        return BlogSummaryViewModel.Map().Concat(i => new BlogViewModel
        {
            PostCount = i.Posts.Count()
        });
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接