【发布时间】:2013-05-09 10:52:51
【问题描述】:
我正在尝试在允许用户创建涉及列、操作和值的过滤条件的网格中实现搜索/过滤。
示例:Column1 包含“somevalue”
当所选列包含字符串类型时,以下代码可以正常工作:
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 没有“包含”方法。在调用“包含”之前,如何首先获取 memberAccess 的 ToString() 值?
注1:“memberAccess”所代表的属性类型在编译时是未知的。
注意 2:lambda 表达式最终被用于无法显式处理 ToString() 的 LINQ 2 实体查询中。 (看看我在下面的尝试)
这是我尝试过的一种解决方案,但在 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;
【问题讨论】:
标签: c# lambda expression