Func needs to supply the Where () method of both IEnumerable and IQueryable

I have Func defined as follows:

Func<Foo, bool> IsSuperhero = x => x.WearsUnderpantsOutsideTrousers;

I can request IEnumerables as follows:

IEnumerable<Foo> foos = GetAllMyFoos();
var superFoos = foos.Where(IsSuperhero);

But when I try to provide the same Func to the Where IQueryable method, I get:

'Cannot convert the original type System.Collections.Generic.IEnumerable to System.Linq.IQueryable.'

What's happening? How to define a Func that will work as a specification for IEnumerable and IQueryable?

+3
source share
1 answer

IQueryableLINQ methods accept Expression Trees , not regular delegates.

, func Expression<Func<Foo, bool>>, :

Expression<Func<Foo, bool>> IsSuperhero = x => x.WearsUnderpantsOutsideTrousers;

IEnumerable<T>, AsQueryable() Compile(), :

IQueryable<Foo> superFoos = foos.AsQueryable().Where(IsSuperhero);
IEnumerable<Foo> superFoos = foos.Where(IsSuperhero.Compile());
+3

Source: https://habr.com/ru/post/1760568/


All Articles