我正在嘗試使用Linq表達式爲IQueryable數據源創建動態where子句。我無法使TryParse函數在其中一個表達式中工作。這裏是我想要做的事:無法獲得double.TryParse在Linq表達式樹中工作
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
參數有關。
UPDATE:
我解決這個問題通過了由公式創建一個靜態的功能它執行的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);
}
是這種方法好不好?有沒有人看到這樣做的缺點?
如果您要將謂詞寫入lambda表達式,它會是什麼樣子? – MarcinJuraszek
沒有必要生成'x == true'。 – SLaks
另外,很少LINQ提供者會處理'TryParse()'。 – SLaks