3

I'm trying to implement this How to specify dynamic field names in a Linq where clause? and getting a compiler error that says:

Cannot resolve method 'Where(System.Linq.Expressions.LambdaExpression

public class Employee
{
    public string Name { get; private set; }
    public int Salary { get; private set; }

    public Employee(string name, int salary)
    {
        Name = name;
        Salary = salary;
    }
}

Then in main method of console app

var employees = new List<Employee>
{
    new Employee("Bob", 45000),
    new Employee("Jane", 25000),
    new Employee("Jim", 5)
};

var eParam = Expression.Parameter(typeof(Employee), "e");

var comparison = Expression.Lambda(
    Expression.LessThan(
        Expression.Property(eParam, "Salary"),
        Expression.Constant(40000)),
    eParam);
var c = from e in employees.Where(comparison) // COMPILER ERROR HERE!!!
    select new {e.Name, e.Salary};

I'm using System.Linq and System.Linq.Expressions. What am I doing wrong here?

EDIT:

The answer is to strongly type the comparison variable and call Compile on it like

var comparison = Expression.Lambda<Func<Employee, bool>>(
    Expression.GreaterThan(
        Expression.Property(eParam, "Salary"),
        Expression.Constant(40000)),
    eParam).Compile();

The query can also be written in method syntax like

var b = employees.Where(comparison);

Instead of calling .Compile(), one can call .AsQueryable() before .Where() on employees also.

Ali
  • 3,373
  • 5
  • 42
  • 54
reggaeguitar
  • 1,795
  • 1
  • 27
  • 48

1 Answers1

7
  1. Your expression has to be strongly typed:

    var comparison = Expression.Lambda<Func<Employee, bool>>(... 
    
  2. Source has to be IQueryable. Call AsQueryable() on your list before calling Where.

Ali
  • 3,373
  • 5
  • 42
  • 54
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
  • This is just casting the result. A cast isn't static typing, this is all dynamically typed. But the cast *is* what you want to be doing. – Servy May 21 '14 at 15:41
  • Is it possible to do the query in method syntax? – reggaeguitar May 21 '14 at 15:47
  • 2
    @reggaeguitar To provide an `Expression` parameter explicitly the query *must* be written using method syntax. It's not possible to do anything else. So yes, it is possible to use method syntax, and that's exactly what you're using in your query to apply the `Where` operator. – Servy May 21 '14 at 15:49