0

I have the following error when try to build an OR expression composed with another two expressions:

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

What I want to do is combine two Expression methods in a third method with OR operator, as follows:

//First expression method
private static Expression<Func<Alarm, bool>> _unacknowledged() 
{
    return alarm => alarm.AcknowledgeDate == null;
}

//Second expression method
private static Expression<Func<Alarm, bool>> _occurring()
{
    return alarm => alarm.OccurrenceFinalDate == null;
}

//Third expression method (that combines the above)
private Expression<Func<Alarm, bool>> _unacknowledgedOrOccurring()
{
    //This is where exception is raised
    var expr = Expression.Lambda<Func<Alarm, bool>>(
        Expression.Or(_unacknowledged(), _occurring())
    );

    return expr;
}

The expected practical clause that I want using the _unacknowledgedOrOccurring() call must be similar to this:

alarmList.Where(alarm => 
    alarm.AcknowledgeDate == null ||
    alarm.OccurrenceFinalDate == null
)

It's possible to do this? What exactly I'm missing?

Thanks in advance.

  • [`Expression.Or`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.expressions.expression.or?view=netframework-4.7.2#System_Linq_Expressions_Expression_Or_System_Linq_Expressions_Expression_System_Linq_Expressions_Expression_System_Reflection_MethodInfo_) is the bitwise OR operator. You need [`Expression.OrElse`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.expressions.expression.orelse?view=netframework-4.7.2). – NetMage Oct 17 '18 at 22:18
  • Yes, I agree with the "duplicate" flag. Unfortunately had not found it previously in searchings. I'll mark this as solved with another referred question. Thanks to all that help in any way. – Renato Lucas Chitolina Oct 18 '18 at 02:38

1 Answers1

0

like @NetMage pointed out, you need Expression.OrElse instead of OR, beside that what's your missing is the your lambda expression required a paremeter list which also the target instance to be invoked on by your _unacknowledged and _occurring.

//Third expression method (that combines the above)
private static Expression<Func<Alarm, bool>> _unacknowledgedOrOccurring()
{       
    var target = Expression.Parameter(typeof(Alarm));
    var or = Expression.OrElse(Expression.Invoke(_unacknowledged(), target), Expression.Invoke(_occurring(), target));
    return Expression.Lambda<Func<Alarm, bool>>(or, target);
}
LeY
  • 659
  • 7
  • 21
  • I would be tempted to re-write the bodies of the two expressions to use a new parameter, and avoid the `Invoke`. – NetMage Oct 17 '18 at 23:07