Create a Lambda Expression With 3 conditions

c# c#-4.0 expression-trees lambda linq

Question

I want to dynamically generate a lambda expression for this:

(o => o.Year == year && o.CityCode == cityCode && o.Status == status)

and I'll say this:

var body = Expression.AndAlso(
               Expression.Equal(
                    Expression.PropertyOrField(param, "Year"),
                    Expression.Constant(year)
               ),
               Expression.Equal(
                    Expression.PropertyOrField(param, "CityCode"),
                    Expression.Constant(cityCode)
               )
               ,
               Expression.Equal(
                    Expression.PropertyOrField(param, "Status"),
                    Expression.Constant(status)
               )
           );

but with regards to this line of code:

Expression.Equal(
                    Expression.PropertyOrField(param, "Status"),
                    Expression.Constant(status)
                )

There was a problem:

Cannot convert from 'System.Linq.Expressions.BinaryExpression' to 'System.Reflection.MethodInfo'

How can I make a lambda expression with three conditions?

1
1
9/4/2017 9:05:10 AM

Accepted Answer

Expression.AndAlso consists of two phrases. Three parameters are required for an overload, however the third argument is aMethodInfo of a technique that performs a and operation on the two operands (additional limitations apply toAndAlso Since it prevents the specifics of truthiness from being overridden, the first operand must still either have atrue and false might be castable to an operatorbool ).

Therefore, what you want is similar to:

(o => o.Year == year && (o.CityCode == cityCode && o.Status == status))

And that would be:

var body = Expression.AndAlso(
    Expression.Equal(
        Expression.PropertyOrField(param, "Year"),
        Expression.Constant(year)
    ),
    Expression.AndAlso(
        Expression.Equal(
            Expression.PropertyOrField(param, "CityCode"),
            Expression.Constant(cityCode)
        ),
        Expression.Equal(
            Expression.PropertyOrField(param, "Status"),
            Expression.Constant(status)
        )
    )
);
3
9/4/2017 9:22:27 AM

Popular Answer

No such thing as an Expression method exists. Three Expressions may be passed as parameters to AndAlso.

Please click the links below.

https://msdn.microsoft.com/en-us/library/bb353520(v=vs.110).aspx

https://msdn.microsoft.com/en-us/library/bb382914(v=vs.110).aspx



Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow