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

  • Home
  • SEARCH
  • 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 7441777
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T11:04:16+00:00 2026-05-29T11:04:16+00:00

I am trying to build an expression tree programmatically. I have in my input,

  • 0

I am trying to build an expression tree programmatically.

I have in my input, a list of condition classes which have the following form:

public class Filter
{
    public string field { get; set; }
    public string operator { get; set; }
    public string value { get; set; }
}

When I build the Expression object I create an Expression for every condition in the following way

foreach ( Filter sf in rules ) {
    Expression ex = sf.ToExpression( query );
    if ( mainExpression == null ) {
        mainExpression = ex;
    }
    else {
        if ( logicalCondition == "AND" ) {
            mainExpression = Expression.And( mainExpression, ex );
        }
        else if ( logicalCondition == "OR" ) {
            mainExpression = Expression.Or( mainExpression, ex );
        }
    }
}

The Filter.ToExpression() method is implemented like this

public override Expression ToExpression( IQueryable query ) {
    ParameterExpression parameter = Expression.Parameter( query.ElementType, "p" );
    MemberExpression memberAccess = null;
    foreach ( var property in field.Split( '.' ) )
        memberAccess = MemberExpression.Property( memberAccess ?? ( parameter as Expression ), property );
    ConstantExpression filter = Expression.Constant( Convert.ChangeType( value, memberAccess.Type ) );
    WhereOperation condition = (WhereOperation)StringEnum.Parse( typeof( WhereOperation ), operator );
    LambdaExpression lambda = BuildLambdaExpression( memberAccess, filter, parameter, condition, value );
    return lambda;
}

Everything works when I have a single condition but when I try to combine expressions using one of the And, Or, AndAlso, OrElse static methods I receive an InvalidOperationException that says:

The binary operator Or is not defined for the types
‘System.Func2[MyObject,System.Boolean]' and
'System.Func
2[MyObject,System.Boolean]’.

I am getting a little bit confused. Can somebody better explain the reasons of the exception and suggest a solution?

Thanks very much!

  • 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-29T11:04:17+00:00Added an answer on May 29, 2026 at 11:04 am

    You’re combining a => a == 3 and a => a == 4 into (a => a == 3) || (a => a == 4), but you should instead be trying to make it a => (a == 3 || a == 4). This is not too hard to do manually, but someone has done it for you already. Look for “Combining Expressions”.

    Edit: as requested, a simple example of how to do this manually.

    Edit 2: it uses ExpressionVisitor which is new to .NET 4, but at MSDN you can find a usable implementation for earlier versions. I’m assuming MSDN code doesn’t qualify as “third party” for your purposes. You only need to change the protected virtual Expression Visit(Expression exp) method to public. And as Enumerable.Zip is unavailable for you and it isn’t necessary, it is gone now.

    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Linq.Expressions;
    
    namespace DemoApp
    {
        <include ExpressionVisitor definition here for .NET 3.5>
    
        public class ExpressionParameterReplacer : ExpressionVisitor
        {
            public ExpressionParameterReplacer(IList<ParameterExpression> fromParameters, IList<ParameterExpression> toParameters)
            {
                ParameterReplacements = new Dictionary<ParameterExpression, ParameterExpression>();
                for (int i = 0; i != fromParameters.Count && i != toParameters.Count; i++)
                    ParameterReplacements.Add(fromParameters[i], toParameters[i]);
            }
            private IDictionary<ParameterExpression, ParameterExpression> ParameterReplacements
            {
                get;
                set;
            }
            protected override Expression VisitParameter(ParameterExpression node)
            {
                ParameterExpression replacement;
                if (ParameterReplacements.TryGetValue(node, out replacement))
                    node = replacement;
                return base.VisitParameter(node);
            }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                Expression<Func<int, bool>> exprA = a => a == 3;
                Expression<Func<int, bool>> exprB = b => b == 4;
                Expression<Func<int, bool>> exprC =
                    Expression.Lambda<Func<int, bool>>(
                        Expression.OrElse(
                            exprA.Body,
                            new ExpressionParameterReplacer(exprB.Parameters, exprA.Parameters).Visit(exprB.Body)),
                        exprA.Parameters);
                Console.WriteLine(exprA.ToString());
                Console.WriteLine(exprB.ToString());
                Console.WriteLine(exprC.ToString());
                Func<int, bool> funcA = exprA.Compile();
                Func<int, bool> funcB = exprB.Compile();
                Func<int, bool> funcC = exprC.Compile();
                Debug.Assert(funcA(3) && !funcA(4) && !funcA(5));
                Debug.Assert(!funcB(3) && funcB(4) && !funcB(5));
                Debug.Assert(funcC(3) && funcC(4) && !funcC(5));
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to build a complex xpath expression which will answer the following
i am trying to build linq expression to solve my problem. I have list
I'm trying to build an expression tree ( still ) but getting further! I
I am trying to create a PredicateBuilder<T> class which wraps an Expression<Func<T, bool>> and
I have been trying to build a regular expression but haven't been able to
I'm trying to build an expression tree for this linq query: so I can
I am trying to build a dynamic Expression Tree like below : Func<IEnumerable<int>, int,
I am trying to build a regular expression to extract the text inside the
I'm trying to build a Java regular expression to match .jar! The catch is
I'm trying build a method which returns the shortest path from one node to

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.