4

我使用动态过滤器,它使用对象属性、运算符和值过滤集合。现在,如果属性是字符串,运算符是“包含”,值是“单词”,则应相应地过滤包含“世界”的过滤对象。

在 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)
4

1 回答 1

3

没有Contains运算符(尽管有名为的方法Contains)。它只对某些类型有意义(如字符串、集合和其他一些类型),但对其他类型没有意义;例如,您将如何定义Contains整数或日期的运算符?

现在,如果您想Contains通过 lambda 表达式将该方法应用于字符串,则必须使用 Expression.Call 生成一个调用该方法的表达式

于 2011-08-25T17:57:25.270 回答