following code works on a collection of type IQueryable:
Expression<Func<Activity, bool>> filter = e => e.IsDeleted && e.CategoryId == 1;
But this expression doesn't work on collections of type IEnumerable.
How I have to modify my expression to get it working?
In my real scenario, my collection object is a navigation property of an entity framework model class: person.Activities.Where(filter);
These are the errors:
Error 1
Instance argument: cannot convert from 'System.Collections.Generic.ICollection<Application.Models.Activity>' to 'System.Linq.IQueryable<Application.Models.Activity>'
Error 2
'System.Collections.Generic.ICollection<Application.Models.Activity>' does not contain a definition for 'Where' and the best extension method overload 'System.Linq.Queryable.Where<TSource>(System.Linq.IQueryable<TSource>, System.Linq.Expressions.Expression<System.Func<TSource,bool>>)' has some invalid arguments
How I have to modify my expression to get it working?
Just use a delegate instead of an expression tree:
Func<Activity, bool> filter = e => e.IsDeleted && e.CategoryId == 1;
If you have to start off with an expression tree, you can either compile that to a delegate:
var filterDelegate = filterExpressionTree.Compile();
Or use AsQueryable to convert your IEnumerable<T> to an IQueryable<T>:
var foo = person.Activies.AsQueryable().Where(filterExpressionTree);
I'd personally avoid expression trees unless you actually need to use them though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With