我正在尝试在一个允许用户创建过滤条件的网格中实现搜索/过滤功能,这些条件涉及到一个列、一个操作和一个值。
例如:列1包含“某些值”。
当所选列包含字符串类型时,以下代码可以正常工作:
case WhereOperation.Contains:
Expression condition = Expression.Call(
memberAccess, //memberAccess is a MemberExpression of the property bound to the column.
typeof(string).GetMethod("Contains"),
Expression.Constant(value.ToString())); // value is what we are checking to see if the column contains.
LambdaExpression lambda = Expression.Lambda(condition, parameter);
break;
然而,当列绑定的属性不是字符串类型(即Int)时,这将失败,因为类型Int没有“Contains”方法。我该如何在调用其上的“Contains”之前首先获取memberAccess的ToString()值?
注1:无法在编译时确定“memberAccess”代表的属性的类型。 注2:Lambda表达式最终被用于LINQ 2实体查询中,该查询不能明确处理ToString()。 (请参见下面我尝试过的内容)
这是我尝试的一个解决方案,但它在LINQ表达式评估时失败,因为LINQ 2实体不支持ToString():
case WhereOperation.Contains:
Expression stringValue = Expression.Call(memberAccess,
typeof(object).GetMethod("ToString"));
Expression condition = Expression.Call(
stringValue,
typeof(string).GetMethod("Contains"),
Expression.Constant(value.ToString()));
LambdaExpression lambda = Expression.Lambda(condition, parameter);
break;