0
我正在使用C#2010 .NET 4.0,並且我有一個List<T>
集合,稱爲returns
,我需要在其上構建動態LINQ查詢。我使用Predicate Builder參考here。使用謂詞生成器的列表<T>上的動態Linq查詢
這工作得很好,如果我有1個篩選條件,但如果我有2個或更多,那麼,當query.compile()
被調用時,我得到這個錯誤:
variable 'tmp' of type 'Check21Tools.IncomingReturn' referenced from scope '', but it is not defined
代碼:
Expression<Func<Check21Tools.IncomingReturn, bool>> query = null;
bool hasFilterItems = false;
if (filterArray != null)
{
foreach (string s in filterArray)
{
if (s == string.Empty)
{ break; }
else
{
hasFilterItems = true;
Int64 id = Int64.Parse(s);
query = query.Or(tmp => tmp.ID == id);
}
}
}
if (hasFilterItems)
{
returns = returns.Where(query.Compile()).CreateFromEnumerable
<Check21Tools.IncomingReturns, Check21Tools.IncomingReturn>();
}
代碼:
public static Expression<Func<T, bool>> Or<T>(
this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
{
if (expr1 == null) return expr2;
return Expression.Lambda<Func<T, bool>>
(Expression.OrElse(expr1.Body, expr2.Body), expr1.Parameters);
}
如果您在使用'名單',你爲什麼要建立一個'表達<>'呢?你可以直接使用代表。 –
2013-03-20 17:15:07
你能舉一個動態的例子嗎?我的'filterArray'對象包含我需要篩選的id。 – 2013-03-20 17:18:01
請參閱http://stackoverflow.com/questions/7094930/linq-to-objects-predicate-builder瞭解不使用表達式樹的PredicateBuilder版本。 – 2013-03-20 17:18:57