Search code examples
c#.netlinqentity-frameworkexpression-trees

Need to build expression tree for max date value


I'm trying to build an expression tree for this linq query: so I can pass in a generic Entity:

this.EntityCollection.Select((ent) => ent.TimeStamp).Max()

I am wanting to create a class that takes a generic Entity and finds the max of its TimeStamp property.

I was trying something like below, but it complains:

ParameterExpression param = Expression.Parameter(typeof(TE), "ent");

MemberExpression prop = Expression.
    Property(param, typeof(TE).GetProperty("TimeStamp").GetGetMethod());

Expression<Func<TE, DateTime>> lambda = Expression.Lambda<Func<TE, DateTime>>(
    prop, new ParameterExpression[] { param });

DateTime maxdate = this.EntityCollection.Select(lambda).Max();

When I compile, I get the following error on the last line of code:

Overload resolution failed because no accessible 'Select' can be called with these arguments:

What am I doing wrong?


Solution

  • (As per comments...)

    The problem is that you're trying to use a mixture of LINQ to Objects (which uses IEnumerable<T> and delegates) and Queryable-based LINQ (which uses IQueryable<T> and expression trees). You can't pass Enumerable<T> an expression tree.

    Three options:

    • Convert the collection to an IQueryable<T> first:

      DateTime maxdate = this.EntityCollection.AsQueryable().Select(lambda).Max();
      
    • Convert the expression tree to a delegate first:

      DateTime maxdate = this.EntityCollection.Select(lambda.Compile()).Max();
      
    • Change your method to accept an IQueryable<T> instead of an IEnumerable<T>