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?
(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 usesIQueryable<T>and expression trees). You can’t passEnumerable<T>an expression tree.Three options:
Convert the collection to an
IQueryable<T>first:Convert the expression tree to a delegate first:
Change your method to accept an
IQueryable<T>instead of anIEnumerable<T>