2013-03-20 3 views
0

저는 C# 2010 .NET 4.0을 사용하고 있으며 이라는 List<T> 콜렉션을 가지고 있으며 동적 LINQ 쿼리를 빌드해야합니다.목록에있는 동적 Linq 쿼리 프레디 티 빌더를 사용하여

나는 술어 작성자 인 here을 사용하고 있습니다.

내가 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); 

} 
+0

당신이'목록 를 사용하는 경우는'왜 <>'전혀'표현을 구축하고있다? 그냥 똑바로 대표를 사용할 수 있습니다. –

+0

동적으로 수행하는 예를 들어 주시겠습니까? 내'filterArray' 객체는 ID를 필터링 할 필요가 있습니다. –

+0

표현 트리를 사용하지 않는 PredicateBuilder 버전은 http://stackoverflow.com/questions/7094930/linq-to-objects-predicate-builder를 참조하십시오. –

답변

0

01에서 작동 술어 빌더의 업데이트 된 버전을 우연히 발견 [한 OP]개 제품 :

public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2) 
    { 
    if (expr1 == null) return expr2; 
    var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>()); 
    return Expression.Lambda<Func<T, bool>> 
       (Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters); 
    }