我使用动态过滤器,使用对象属性,运算符和值过滤集合。现在,如果属性是字符串,则运算符为“contains”,值为“word”,则应相应地过滤包含“world”的过滤对象。
在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)
答案 0 :(得分:3)
没有Contains
运算符(尽管方法名为Contains
)。它只适用于某些类型(如字符串,集合和其他一些类型),但不适用于其他类型;例如,如何为整数或日期定义Contains
运算符?
现在,如果要通过lambda表达式将Contains
方法应用于字符串,则必须使用Expression.Call生成一个调用该方法的表达式。