2017-09-04 1 views
1

Ich möchte für diese dynamisch einen Lambda-Ausdruck erstellen:erstellen Lambda-Ausdruck mit 3 Bedingungen

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

und ich schreibe dies:

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

aber für dieses Stück Code:

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

Ich habe einen Fehler:

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

Wie kann ich einem Lambda-Ausdruck 3 Bedingungen hinzufügen?

+0

was 'status'? –

+0

@MongZhu I Update Ques. Bitte sehen Sie es wieder – Arian

+8

'AndAlso' ist ein' BinaryExpression', d. H. Hat 2 Operanden. Wenn Sie mehr als 2 haben, müssen Sie mehrere 'AndAlso', d. H.' AndAlso (AndAlso (op1, op2), op3) usw. miteinander ketten. –

Antwort

2

Expression.AndAlso nimmt zwei Ausdrücke. Es gibt eine Überladung, die drei Argumente benötigt, aber das dritte Argument ist eine MethodInfo einer Methode, die eine und Operation auf den zwei Operanden implementiert (es gibt weitere Einschränkungen im Fall AndAlso, da es die Details der Wahrheit nicht erlaubt überschrieben werden, so dass der erste Operand immer noch entweder einen Operator true und false haben muss oder auf bool castbar sein muss).

Also, was Sie wollen, ist das Äquivalent von:

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

Welche wäre:

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