Reputation: 16120
I have a Func defined as follows:
Func<Foo, bool> IsSuperhero = x => x.WearsUnderpantsOutsideTrousers;
I can query IEnumerables like this:
IEnumerable<Foo> foos = GetAllMyFoos();
var superFoos = foos.Where(IsSuperhero);
But when I try to supply the same Func to the Where method of an IQueryable, I get:
'Cannot convert source type System.Collections.Generic.IEnumerable to System.Linq.IQueryable.'
What's going on? How can I define a Func which will work as a specification for both IEnumerable and IQueryable?
Upvotes: 3
Views: 470
Reputation: 887451
IQueryable
's LINQ methods take Expression Trees, not normal delegates.
Therefore, you need to change your func
variable to an Expression<Func<Foo, bool>>
, like this:
Expression<Func<Foo, bool>> IsSuperhero = x => x.WearsUnderpantsOutsideTrousers;
To use the same variable with an IEnumerable<T>
, you'll need to call AsQueryable()
or Compile()
, like this:
IQueryable<Foo> superFoos = foos.AsQueryable().Where(IsSuperhero);
IEnumerable<Foo> superFoos = foos.Where(IsSuperhero.Compile());
Upvotes: 3