Question

I'm using C# 2010 .NET 4.0 and I have a List<T> collection called returns that I need to build a dynamic LINQ query on.

I'm utilizing the Predicate Builder referenced here.

This works fine if I have 1 filter criteria, but if I have 2 or more, then, when the query.compile() is called, I get this error:

variable 'tmp' of type 'Check21Tools.IncomingReturn' referenced from scope '', but it is not defined

Code:

  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>();
  } 

Code:

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

 }
Était-ce utile?

La solution

[The OP has] stumbled across an updated version of the predicate builder that works on List<T> objects:

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);
  }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top