我正在尝试使用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);
一切正常,直到分配了
results
,然后出现以下错误:variable 'tempN' of type 'System.Double' referenced from scope '', but it is not defined
我在这里想念什么?我怀疑这与double.TryParse函数中的第二个参数是
out
参数有关。更新:
我通过创建一个执行TryParse的静态函数并从Expression中调用此静态函数来解决了这个问题:
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);
}
这种方法行吗?有人看到这样做有什么缺点吗?
最佳答案
Tryparse使用out参数进行检查。使用tryparse创建扩展方法,然后从linq调用扩展方法
关于c# - 无法获得double.TryParse在Linq表达式树中工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31350838/