Create a Lambda Expression With 3 conditions

前端 未结 2 1474

I want to create a lambda expression dynamically for this:

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


        
2条回答
  •  粉色の甜心
    2020-12-04 04:01

    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)
            )
        )
    );
    

提交回复
热议问题