我使用动态过滤器,它使用对象属性、运算符和值过滤集合。现在,如果属性是字符串,运算符是“包含”,值是“单词”,则应相应地过滤包含“世界”的过滤对象。
在 Linq 中,我有表达式。Equal
, NotEqual
, GreaterThanOrEqual
,LessThanOrEqual
但没有“ Contains
”。如何更换它?
考虑以下代码(在 VB.NET 中,但没关系)
Select Case compOp
Case ComparisonOperator.Contains
' ?????? WHAT HERE ???? '
filterExpression = Expression.Lambda(Of Func(Of PropertyType, Boolean))(Expression.Equal(myObjPropertyParam, myConstExpression), myObjParam)
Case ComparisonOperator.Different
filterExpression = Expression.Lambda(Of Func(Of PropertyType, Boolean))(Expression.NotEqual(myObjPropertyParam, myConstExpression), myObjParam)
Case ComparisonOperator.Equal
filterExpression = Expression.Lambda(Of Func(Of PropertyType, Boolean))(Expression.Equal(myObjPropertyParam, myConstExpression), myObjParam)
Case ComparisonOperator.GreatherThanOrEqual
filterExpression = Expression.Lambda(Of Func(Of PropertyType, Boolean))(Expression.GreaterThanOrEqual(myObjPropertyParam, myConstExpression), myObjParam)
Case ComparisonOperator.LessThanOrEqual
filterExpression = Expression.Lambda(Of Func(Of PropertyType, Boolean))(Expression.LessThanOrEqual(myObjPropertyParam, myConstExpression), myObjParam)
End Select
编辑:
使用的解决方案,感谢 Thomas Levesque 和 Jon Skeet )
Dim expr As Expression = Nothing
Select Case compOp
Case ComparisonOperator.Contains
expr = Expression.Call(myObjPropertyParam, "Contains", Nothing, constantExpression)
Case ComparisonOperator.Different
expr = Expression.NotEqual(myObjPropertyParam, constantExpression)
Case ComparisonOperator.Equal
expr = Expression.Equal(myObjPropertyParam, constantExpression)
Case ComparisonOperator.GreatherThanOrEqual
expr = Expression.GreaterThanOrEqual(myObjPropertyParam, constantExpression)
Case ComparisonOperator.LessThanOrEqual
expr = Expression.LessThanOrEqual(myObjPropertyParam, constantExpression)
End Select
filterExpression = Expression.Lambda(Of Func(Of PropertyType, Boolean))(expr, myObjParam)