1

I want to create a lambda expression dynamically for this:

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

and I write 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 for this chunk of code:

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

I got an error:

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

How I can add 3 conditions to a lambda expression?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Arian
  • 12,793
  • 66
  • 176
  • 300

2 Answers2

5

Expression.AndAlso takes two expressions. There is an overload that takes three arguments, but that third argument is a MethodInfo of a method that implements an and operation on the two operands (there are further restrictions in the case of AndAlso as it doesn't allow the details of truthiness to be overridden, so the first operand will still need to either have a true and false operator or be castable to bool).

So what you want is the equivalent of:

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

Which 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)
        )
    )
);
Jon Hanna
  • 110,372
  • 10
  • 146
  • 251
-1

There is no method called Expression.AndAlso which can take 3 Expressions as arguments.

Please refer below links,

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

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

Ravi Kumar G N
  • 396
  • 1
  • 3
  • 11