【问题标题】:Combine several similar SELECT-expressions into a single expression将几个相似的 SELECT 表达式组合成一个表达式
【发布时间】:2026-01-24 22:55:01
【问题描述】:

如何将几个相似的 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..;
            }
        }
    }

【问题讨论】:

  • 显示列表中的数据。这是必要的,以避免从数据库中加载不必要的字段。

标签: c# linq linq-expressions


【解决方案1】:

不简单;您需要重写所有表达式 - 好吧,严格来说,您可以回收其中的大部分,但问题是每个表达式都有不同的 x(即使看起来相同),因此您需要使用访问者用 final 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);
    }
}

这使用了找到的第一个表达式中的构造函数,因此您可能想要彻底检查所有其他人在各自的NewExpressions 中使用普通构造函数。不过,我已经把它留给读者了。

编辑:在 cmets 中,@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);        
}

【讨论】:

  • +1 用于编写所有代码。通过用 LINQ 调用和新的 Parameter 替换嵌套循环,它可以变得更简单
  • @Slaks 也许,也许。不过它已经足够复杂了——读者可能有更多的机会在更程序化的布局中去理解它
  • @Slaks - 添加,只是为了好玩
  • 我已经修改了你的代码并且工作正常。但我想使用 Expression> selector1 = x => new { Name = x.Name } 这样的表达式;而不是 Expression> selector1 = x => new AgencyDTO { Name = x.Name };我怎样才能让它与这种匿名类型一起工作?如果使用匿名类型,则此表达式 (MemberInitExpression)selector.Body 会中断
【解决方案2】:

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

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

【讨论】:

  • 其实是MemberInitExpressionNewExpression只是ctor);虽然可以做到(添加)
【解决方案3】:

如果其他人偶然发现了与我类似的用例(我的选择根据所需的详细程度针对不同的类):

简化场景:

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()
        });
    }

【讨论】: