Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 5977077
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T21:19:08+00:00 2026-05-22T21:19:08+00:00

How to combine several similar SELECT-expressions into a single expression? private static Expression<Func<Agency, AgencyDTO>>

  • 0

How to combine several similar SELECT-expressions into a single expression?

   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..;
            }
        }
    }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-22T21:19:09+00:00Added an answer on May 22, 2026 at 9:19 pm

    Not simple; you need to rewrite all the expressions – well, strictly speaking you can recycle most of one of them, but the problem is that you have different x in each (even though it looks the same), hence you need to use a visitor to replace all the parameters with the final x. Fortunately this isn’t too bad in 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);
        }
    }
    

    This uses the constructor from the first expression found, so you might want to sanity-check that all of the others use trivial constructors in their respective NewExpressions. I’ve left that for the reader, though.

    Edit: In the comments, @Slaks notes that more LINQ could make this shorter. He is of course right – a bit dense for easy reading, though:

    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);        
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need to create and combine several expressions for child entity into one to
In Clojure, I would like to combine several maps into a single map where
Hey, I was trying to combine several arrays of type double into one single
I would like to combine several lists or arrays into a single record array.
I have been asked to combine multiple (several hundred) svn repositories into a single
I want to combine a textbox and several validator controls into 1 usercontrol. Is
I wonder what's the best approach to combine several CCSprites dynamically into one grouped
I am trying to combine a bunch of similar methods into a generic method.
Is it possible to combine several externals into one directory? e.g.: $ svn propget
I want to combine several PDFs into one by appending the pages of each

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.