use*_*023 5 c# linq reflection lambda expression-trees
我正在尝试使用 Linq 表达式为 IQueryable 数据源创建动态 where 子句。我无法让 TryParse 函数在其中一个表达式中工作。这是我想要做的:
IQueryable<trial_global> globalTrials = _trialsRepository.GlobalDataFiltered(filterId).AsQueryable();
BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Static;
MethodInfo tryParseMethod = typeof(double).GetMethod("TryParse", bindingFlags, null, new Type[] { typeof(string), typeof(double).MakeByRefType() }, null);
Expression tempN = Expression.Parameter(typeof(double), "tempN");
Expression left = Expression.Call(tryParseMethod, new[] { metricReference, tempN });
Expression right = Expression.Constant(true);
Expression predicateBody = Expression.Equal(left, right);
MethodCallExpression whereCallExpression = Expression.Call(
typeof(Queryable),
"Where",
new Type[] { globalTrials.ElementType },
globalTrials.Expression,
Expression.Lambda<Func<trial_global, bool>>(predicateBody, new ParameterExpression[] { pe })
);
var results = globalTrials.Provider.CreateQuery<trial_global>(whereCallExpression);
Run Code Online (Sandbox Code Playgroud)
一切正常,直到results
被分配到我收到以下错误的地方:
variable 'tempN' of type 'System.Double' referenced from scope '', but it is not defined
Run Code Online (Sandbox Code Playgroud)
我在这里缺少什么?我怀疑它与作为参数的 double.TryParse 函数中的第二个out
参数有关。
更新:
我通过创建一个静态函数来解决这个问题,该函数执行 TryParse 并从表达式中调用这个静态函数:
public static bool IsStringNumeric(string checkStr)
{
double num = 0;
return double.TryParse(checkStr, out num);
}
public IQueryable<trial_global> GetTrials(IQueryable<trial_global> globalTrials, Metric metric)
{
ParameterExpression pe = Expression.Parameter(typeof(trial_global), "trial_global");
MemberExpression metricReference = Expression.Property(pe, metric.metric_name);
Expression predicateBody = Expression.Call(typeof(GlobalTrialsRepository).GetMethod("IsStringNumeric", new Type[] { typeof(string) }), metricReference);
MethodCallExpression whereCallExpression = Expression.Call(
typeof(Queryable),
"Where",
new Type[] { globalTrials.ElementType },
globalTrials.Expression,
Expression.Lambda<Func<trial_global, bool>>(predicateBody, new ParameterExpression[] { pe })
);
return globalTrials.Provider.CreateQuery<trial_global>(whereCallExpression);
}
Run Code Online (Sandbox Code Playgroud)
这个方法好吗?有没有人看到这样做的任何缺点?
归档时间: |
|
查看次数: |
750 次 |
最近记录: |